Java 通过单击鼠标按钮绘制和存储对象
我试图在每次单击时绘制圆形对象,然后将每个圆形对象存储到Arraylist中,我不知道为什么我的程序不工作!如果我删除了arraylist和创建新圆形对象的线条,程序将正常工作。如何使程序将所有回路对象存储到Arraylist中Java 通过单击鼠标按钮绘制和存储对象,java,swing,draw,Java,Swing,Draw,我试图在每次单击时绘制圆形对象,然后将每个圆形对象存储到Arraylist中,我不知道为什么我的程序不工作!如果我删除了arraylist和创建新圆形对象的线条,程序将正常工作。如何使程序将所有回路对象存储到Arraylist中 import javax.swing.JPanel; import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseAdapter; import
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(20);
repaint();
}
}); // end addMouseListener
}
public void paintComponent (Graphics g) {
super.paintComponent(g);
g.setColor(new Color(rColor, gColor, bColor));
g.fillOval(xStart, yStart, radius, radius);
xxx.add(new Circle());
}
private class Circle {
private int x;
private int y;
private int r;
private int rcol;
private int gcol;
private int bcol;
public Circle()
{
x=xStart;
y=yStart;
r=radius;
rcol= rColor;
gcol= gColor;
bcol= bColor;
}
}
}
不要在
paintComponent
方法中添加新形状,paintComponent
可以出于多种原因调用,其中许多原因您无法控制,而是在触发mouseClicked
事件时创建它
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(20);
xxx.add(new Circle(xStart, yStart, new Color(rColor, gColor, bColor), radius));
repaint();
}
然后在paintComponent
中,在ArrayList
中循环并绘制圆
public void paintComponent (Graphics g) {
super.paintComponent(g);
for (Circle c : xxx) {
g.setColor(c.getColor());
g.fillOval(c.getX(), c.getY(), c.getRadius(), c.getRadius());
}
}
现在,您必须修改Circle
类,以提供CircleObj
可以用来实际绘制圆的getter
public void paintComponent (Graphics g) {
super.paintComponent(g);
for (Circle c : xxx) {
g.setColor(c.getColor());
g.fillOval(c.getX(), c.getY(), c.getRadius(), c.getRadius());
}
}
或者,您可以使用Java中提供的
Shape
s API…查看更多详细信息…非常感谢兄弟。