我有一个 JFrame,里面有随机的圆圈(它们是随机生成的)。我想通过鼠标单击从 Jframe 中删除选定的圆圈,并根据删除增加分数。.有什么想法吗?
“我有一个计时器,可以在屏幕上创建一个新的圆圈。 我还使用列表来存储创建的圈子。 (引用公众圈类) 我还有一个收缩功能,可以通过减小半径来及时缩小圆圈。”
private static final int WIDTH = 700;
private static final int HEIGHT = 700;
public int x, y;
private static final int D_W = 500;
private static final int D_H = 500;
private List<Circle> circles;
Random random = new Random();
public int randRadius;
public int delay = 50;
public static int Life=10;
public static int Score=0;
private List<Circle> circles;
public static int Score=0;
public GameModel() {
setSize(WIDTH,HEIGHT); //setting the Frame width and height
circles = new ArrayList<>();
Timer timer = new Timer(250, new ActionListener() {
//timer for creating a new ball on JFrame
@Override
public void actionPerformed(ActionEvent e) {
int randX = random.nextInt(D_W); //or whatever the width of your panel is
int randY = random.nextInt(D_H); //or whatever the height of your panel is
randRadius = random.nextInt(101) + 50; //radius
Color color = Color.BLUE;
Circle circle = new Circle(randRadius, color, randX, randY);
circles.add(circle);
update(); //it is simply repaint();
}
});
timer.start();
}
@Override
protected void paintComponent(Graphics g) { //draw the circle randomly
super.paintComponent(g);
for (Circle circle : circles) {
circle.drawCircle(g);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(D_W, D_H);
}
public class Circle { //class for shrinking the balls in time
public int radiuss, x, y;
Color color;
public Circle(int radius, Color color, int x, int y) {
this.radiuss = radius;
this.color = color;
this.x = x;
this.y = y;
ActionListener counter = new ActionListener(){
public void actionPerformed(ActionEvent evt){
update();
radiuss--;
}};
new Timer (delay, counter).start();
}
public void drawCircle(Graphics g) {
g.setColor(color);
g.fillOval(x, y, radiuss * 2, radiuss * 2);
}
}
private class ClickCircle extends MouseAdapter {
public void mousePressed(MouseEvent e) {
selected = null;
...
if (selected != null) {
Score++;
System.out.println("Score" + Score);
}
}
}
最佳答案
不要创建自己的 Circle 类。相反,您可以使用 Ellipse2D.Double(...)
类。
Ellipse2D 类实现 Shape
接口(interface)。 Shape
接口(interface)实现了 contains(...)
方法。因此,您可以遍历列表中的所有对象并检查 Shape
是否包含鼠标点。
所以我会把你的“Circle”类改为“ShapeInfo”类。这个类将包含两个属性:
- 形状
- 颜色
所以你的基本代码是:
//Circle circle = new Circle(randRadius, color, randX, randY);
//circles.add(circle);
Shape shape = new Ellipse2D.Double(...);
ShapeInfo info = new ShapeInfo(shape, color);
shapes.add( info );
将来您甚至可以添加矩形
形状或您想要的任何其他形状到列表中。
参见Playing With Shapes有关此概念的更多一般信息。
update(); //it is simply repaint();
然后只需调用 repaint()。这是调用以确保正确重新绘制组件的正确方法。
关于java - 如何从圆列表中选择圆以从 JFrame 中删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53683402/