gpt4 book ai didi

java - 通过单击鼠标按钮绘制和存储对象

转载 作者:行者123 更新时间:2023-12-02 05:23:52 24 4
gpt4 key购买 nike

我试图通过每次单击绘制圆形对象,然后将每个圆形对象存储到数组列表中,我不知道为什么我的程序无法工作!如果我删除了数组列表和创建新圆形对象的行,该程序将运行。我如何让我的程序将所有电路对象存储到 Arraylist 中?

 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;

}




}

}

======

import javax.swing.JFrame;
import java.awt.BorderLayout;

public class HW3 {
public static void main (String[] arg) {
JFrame frame = new JFrame("Circles");
CircleObj canvas = new CircleObj();

frame.add(canvas, BorderLayout.CENTER);
frame.setBounds(250, 98, 600, 480);
//frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
} // end main
} //end HW3

最佳答案

不要在 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 来实际绘制圆圈...

或者,您可以使用 Java 中提供的 Shapes API...查看 Working with Geometry了解更多详情...

关于java - 通过单击鼠标按钮绘制和存储对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26247499/

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