我有这个程序,每次点击画一个圆圈,我的问题是当我点击其他地方时它会擦除圆圈。如何让程序保持圆圈而不删除前一个?我还想创建一个擦除所有圆圈的按钮,是否有方法可以删除所有内容?
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Random;
public class CircleObj extends JPanel {
private int rColor;
private int gColor;
private int bColor;
private int radius;
private Random rand = new Random();
private int xStart;
private int yStart;
ArrayList <Circle> xxx ;
public CircleObj () {
xxx = new ArrayList<Circle>();
addMouseListener(new MouseAdapter() {
public void mouseClicked (MouseEvent e) {
xStart = e.getX();
yStart = e.getY();
rColor = rand.nextInt(256);
gColor = rand.nextInt(256);
bColor = rand.nextInt(256);
radius = rand.nextInt(100);
xxx.add(new Circle(xStart, yStart,rColor, gColor, bColor, radius));
System.out.println(xxx);
repaint();
}
}); // end addMouseListener
}
public void paintComponent (Graphics g) {
super.paintComponent(g);
g.setColor(new Color(rColor, gColor, bColor));
g.fillOval(xStart, yStart, radius, radius);
}
class Circle {
private int x;
private int y;
private int rad;
private int rcol;
private int gcol;
private int bcol;
public Circle (int xValue, int yValue,int redValue, int greenValue, int blueValue, int radValue) {
x = xValue;
y = yValue;
rad = radValue;
rcol = redValue;
gcol = greenValue;
bcol = blueValue;
}
public String toString (){
return String.format("X value is: " + x + "\nY value is: " + y + "\nRadius value is: " +rad +
"\nRed value is: "+ rcol+ "\nGreen value is: "+ gcol + "\nBlue value is: "+bcol+ "\n\n");
}
}
}
答案 0 :(得分:3)
你有一个圆圈列表,看起来对我不熟 - 每当你点击你添加一个圆圈但你只画一个圆圈你点击...
public void paintComponent (Graphics g) {
super.paintComponent(g);
//g.setColor(new Color(rColor, gColor, bColor));
//g.fillOval(xStart, yStart, radius, radius);
for (Circle circle: xxx){
g.setColor(new Color(circle.rcol, circle.gcol, circle.bcol));
g.fillOval(circle.x, circle.y, circle.rad, circle.rad);
}
}
使用此方法为您的屏幕添加圈子 - 如果您想删除它们,按钮或任何其他活动,请拨打清除列表的xxx.clear()
(不要忘记{{1}清除清单后......