我正在编写简单的 Paint 程序,你可以通过拖动鼠标来绘制任何你想要的东西。您可以更改画笔的颜色和大小,但是在这个版本中,当我更改画笔的颜色或大小时,当我通过拖动鼠标再次开始绘制时,之前绘制的所有内容也会更改。我曾尝试在paintComponent 方法中使用getGraphics 方法,但我可能做错了,因为它对我没有帮助。有什么想法可以解决这个问题吗?谢谢你。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JPanel;
public class PaintPanel extends JPanel{
private int pointCount = 0;
private Point points[] = new Point[10000];
private Color currentColor;
private int pointSize;
public PaintPanel(){
setBackground(Color.WHITE);
setDefaultColor();
setDefaultPointSize();
addMouseMotionListener(
new MouseMotionAdapter() {
public void mouseDragged(MouseEvent event){
if(pointCount < points.length){
points[pointCount] = event.getPoint();
pointCount++;
repaint();
}
}
}
);
}
public void setColor(Color newColor){
currentColor = newColor;
}
public void setDefaultColor(){
currentColor = Color.BLACK;
}
public void setPointSize(int size){
pointSize = size;
}
public void setDefaultPointSize(){
pointSize = 6;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(currentColor);
for(int i = 0; i < pointCount; i++)
g.fillOval(points[i].x,points[i].y,pointSize,pointSize);
}
}
没有集合可以选择吗?