java - JFrame 菜单被绘制,图形在 JFrame 调整大小时消失

标签 java swing components jframe paint

我是一名高中生,正在为计算机科学课做期末项目。我的任务是制作一个简单的绘画应用程序,但是我遇到了一些问题。其中包括:调整窗口大小时会删除绘制的图像,并且我可以在窗口中的菜单上绘制图像。

我相信我正在菜单上绘图,因为我正在使用 JFrame 本身的图形对象。但是我找不到任何替代方案。我尝试过制作单独的组件来绘制,甚至使用 BufferedImage,但我的尝试都没有成功。

这是我的代码:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.*;

public class Paint implements MouseMotionListener{

private JFrame window;
private drawingComponent pComp;
private int xPos; //xPos of mouse;
private int yPos; //yPos of mouse;
private Color color; // new color
private JTextArea sizeBox;

private int brushShape = 0;

public static void main(String[] args) {
    Paint paint = new Paint();
    paint.ImplementGUI();
}

public Paint() {
    this.pComp = new drawingComponent();
    this.window = new JFrame("JPaint");
    this.window.setSize(500, 500);
    this.window.setVisible(true);
    this.window.addMouseMotionListener(this);
    this.window.add(this.pComp);
}

public void ImplementGUI() {
    JMenuBar menu = new JMenuBar();
    JMenu brush = new JMenu("Brush Settings");
    JMenu brushShape = new JMenu("Shape");
    brush.setSize(100,100);
    brush.add(brushShape);
    menu.add(brush);
    menu.setSize(window.getWidth(), 20);
    menu.setVisible(true);

    this.sizeBox = new JTextArea("Brush Size:");
    this.sizeBox.setText("20");
    brush.add(this.sizeBox);

    this.window.setJMenuBar(menu);
}

public void mouseDragged(MouseEvent pMouse) {
    if (pMouse.isShiftDown() == true) {
        this.pComp.paint(this.window.getGraphics(), pMouse.getX(), pMouse.getY(),
                         window.getBackground(), Integer.parseInt(sizeBox.getText()));
    }
    else {
        this.pComp.paint(this.window.getGraphics(), pMouse.getX(), pMouse.getY(),
                         color, Integer.parseInt(sizeBox.getText()));
    }
}

public void mouseMoved(MouseEvent pMouse) {
}

}

class drawingComponent extends JComponent {
    public void paint(Graphics g, int x, int y, Color color, int size) {
        g.setColor(color);
        g.fillOval(x-(size/2), y-(size/2), size, size); // 10 is subtracted from
        // coordinates so the mouse pointer is at the exact middle of the brush.
    }
}

如何解决这个问题?

最佳答案

切勿使用 getGraphics() 方法进行绘画。正如您所注意到的,效果只是暂时的。

自定义绘制是通过重写paintComponent()方法而不是paint()方法来完成的。

参见Custom Painting Approaches有关如何在面板上绘制多个对象的几个示例。

关于java - JFrame 菜单被绘制,图形在 JFrame 调整大小时消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6240923/

相关文章:

java - 我尝试在 mysql 表中插入数据

java - 从 Service 向 Activity 发送一条简单的消息

java - 如果我们知道索引,则从列表中检索字符串

java - 在模式中动态添加 JLabel 但最后一个无法正常工作

user-interface - Java Swing - 半透明组件

ios - 使用 UIPickerView 上第一个组件的值更改其余组件

java - 扩展OutputStream类;写(int)方法

java - 文本从 JSpinner 到 JTextArea

java - Stacktrace 的异常仅包含 Java 库调用

angular - 通过 Angular 组件将函数作为参数传递给(单击)事件