![](/img/trans.png)
[英]How do I go about allowing a user to input as many strings as they want while also checking it against an array?
[英]How would I go about checking if the user clicked on a square generated by fillRect & perform an action when they do so?
我在 Java 中編寫一個游戲,關於躲避橙色紅色方塊並單擊它們以刪除它們。 但是,我需要弄清楚當首先單擊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) { }
點擊Canvas.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);
}
}
我希望它能讓你了解你想在游戲中做什么
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.