2017-03-16 82 views
2

我正在为我的高中Java Java编程课上的战列舰游戏工作(迄今为止失败很糟糕)。到目前为止,我拥有计算机和玩家的游戏板,并且我已经为计算机生成了这些船,并确保玩家可以沉没它们。两个板都有一个网格布局,并且它们中的每一个都被分配给玩家和计算机的二维数组,并且是特定网格布局的一部分(说实话,我并不真正了解很多代码,因为它是由我们的老师提供的,所以我不能确定哪些部分是相关的,哪些不是 - 这也是为什么我没有发布我的任何代码)。在Java中点击了哪个按钮?

我现在要做的就是让玩家放置他们的船只,让他们通过点击棋盘选择一个起始位置。

inside of a for loop 
      1: a button in buttonsPlayer is clicked 
      2: when a button is clicked, the two coordinates are calculated and stored as x, y coordinates 
      3: a ship is generated with the starting coordinates of x, y 

我知道如何生成一个随机的x和y起始坐标的船,就像我之前做过的那样。点击按钮后,有没有办法在数组中获取按钮的编号?

(我不喜欢就在这里5个其他线程,似乎问同样的问题看一遍,但我真的不得到任何答案)

回答

0

你可以创建一个类,extends JButton并增添了更多的功能到JButton像这样:

public class BoardPiece extends JButton{ 
    private int x,y; 
    //rest of class including getters and setters 
} 

这会随之带来的JButton所有功能,您可以添加基本上元数据约每平方米。

然后在你的事件监听器,你将能够只是调用.getX().getY()像这样:

boardPiece.addActionListener((e)->{ 
    BoardPiece clicked = (BoardPiece)e.getSource(); 
    int x = clicked.getX(); 
    // and so on 

}); 
0

一个JButton有一个“动作指令”,它允许你把信息在它从其他distinquish它纽扣。

使用

JButton.setActionCommand 
JButton.getActionCommand 

所以,如果你编码按钮的坐标,在该字符串,在你的ActionListener可以

JButton b = (JButton) eventListener.getSource(); 

String cmd = b.getActionCommand(); 

,然后的过程,在cmd字符串来找出你在棋盘上的位置。

0

你可以给JButton一个ActionCommand,

JButton button1 = new JButton("Button 1"); 
    button1.setActionCommand("Button1id");` 

那么如果要实现ActionListener来监听buttonpress,您可以编写

@Override 
    public void actionPerformed(ActionEvent ae) { 
     String buttonid = ae.getActionCommand(); 
    } 

代码通过检查buttonid的价值,你就会知道哪个按钮被按下。

+0

setActionCommand中的“Button1id”是什么意思?它只是一个确定行动的名称,还是需要具体的东西? –

+0

这只是一些东西来识别它。它可以是任何字符串。你可以把一些数据放在那里,就像你可以解析的数字一样。 –