gpt4 book ai didi

java - 使用 Graphics2D 绘制 JPanel 程序在调整窗口大小时消失

转载 作者:行者123 更新时间:2023-12-02 02:54:44 25 4
gpt4 key购买 nike

我正在尝试创建一个 JPanel 来制作一个简单的绘画程序,每当用户拖动鼠标时就会进行绘画。然而,在调整窗口大小后,我已经绘制的图形消失了。这是 PaintPanel 类:

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 以绘制每个对象

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

关于java - 使用 Graphics2D 绘制 JPanel 程序在调整窗口大小时消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43294273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com