使用 Graphics2D 绘制 JPanel 程序在调整大小时消失 Window

Paint JPanel Program using Graphics2D Disappears when Resizing Window

我正在尝试创建一个 JPanel 来制作一个简单的绘画程序,该程序在用户拖动鼠标时进行绘画。但是,在调整 window 的大小时,我已经绘制的图形消失了。这是 PaintPanel class:

public class PaintPanel extends JPanel {    

private static final long serialVersionUID = 4267027584083413157L;

private class MouseMotionHandler implements MouseMotionListener {

    public void mouseDragged(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();

        Graphics2D g2 = (Graphics2D)getGraphics();

        g2.setPaint(color);         
        g2.fillOval(x, y, size, size);
    }


    public void mouseMoved(MouseEvent e) {

    }

}

class JSliderHandler implements ChangeListener {
    @Override
    public void stateChanged(ChangeEvent e) {
        JSlider colorChange = (JSlider)e.getSource();
        if (!colorChange.getValueIsAdjusting()) {
            colVal = (int)colorChange.getValue();
            color = new Color(colVal, colVal, colVal);
            System.out.print(colVal);
        }
    }
}

class JSpinnerHandler implements ChangeListener {
    @Override
    public void stateChanged(ChangeEvent e) {
        JSpinner thickChange = (JSpinner)e.getSource();
        size = (int)thickChange.getValue();
    }
}


private Color color;
private int colVal = 0;
private int   size;


public PaintPanel() {     

    color = new Color(colVal, colVal, colVal);
    size  = 8;

    addMouseMotionListener(new MouseMotionHandler());        
}
}

a simple paint program that paints whenever the user drags their mouse.

参见Custom Painting Approaches。它演示了两种常用的自定义绘画方式:

  1. 将要绘制的对象存储在一个ArrayList中,然后在paintComponent(...)方法中遍历ArrayList来绘制每个Object

  2. 直接绘制到 BufferedImage,然后只绘制 BufferedImage。