gpt4 book ai didi

java - 我将如何检查用户是否单击了 fillRect 生成的正方形并在单击时执行操作?

转载 作者:行者123 更新时间:2023-12-02 08:42:34 25 4
gpt4 key购买 nike

我正在用 Java 编写一个关于躲避橙色红色方 block 并单击它们将其删除的游戏。但是,我需要弄清楚如何编写代码来在首先单击 fillRect 时执行操作,如果这是不可能的,那么至少有一种方法可以确定使用的位置单击或检查他们是否总体上单击了某个区域?

public void mouseClicked(MouseEvent e) { System.out.println(e.getXOnScreen()); }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }

最佳答案

ClickCanvas.java

public final class ClickCanvas extends Canvas
{
private final List<Rectangle> squares=new ArrayList();

ClickCanvas()
{
addMouseListener(new OnClick());

for(int x=5;x<=305;x+=150)//3 by 3 grid of squares to click
{
squares.add(new Rectangle(x,5,50,50));
squares.add(new Rectangle(x,155,50,50));
squares.add(new Rectangle(x,305,50,50));
}
}

@Override
public void paint(Graphics g) //Painting Your Squares Here Called By Swing
{
super.paint(g);

Dimension size=getSize();

g.setColor(Color.WHITE);

g.fillRect(0,0,size.width,size.height);

g.setColor(Color.ORANGE);

squares.forEach(square->g.fillRect(square.x,square.y,square.width,square.height));
}

private class OnClick extends MouseAdapter
{
@Override
public void mousePressed(MouseEvent m)
{
squares.removeIf(square->square.contains(m.getPoint()));//You do Your Action Here in this case i remove the square if it contains the mouse point

repaint(); //Repaint The Canvas To Now Redraw Remaining Squares

if(squares.isEmpty())
{
JOptionPane.showMessageDialog(null,"Congrats You Win");

System.exit(0);
}
}
}
}

主类

public class ClickTest 
{
public static void main(String args[])
{
JFrame frame=new JFrame("Click Test");

frame.add(new ClickCanvas());

frame.setSize(400,450);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);
}
}

我希望它能让您了解自己想在游戏中做什么

关于java - 我将如何检查用户是否单击了 fillRect 生成的正方形并在单击时执行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61279920/

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