我正在嘗試使用Java Swing編寫一個Battleship程序,目前我有一個使兩個網格的類。我試圖找出哪個按鈕被點擊的位置,所以我可以稍後使用它來放置鏡頭等等。不幸的是,我在這方面遇到了一些麻煩。Java Swing ActionListener顯示JButton數組
我已經得到了使用actionPerformed方法打印出來的所有東西的對象,但我只想要grid [x] [y]。我如何去做這件事?
在此先感謝您的幫助。
package testapp;
/**
*
* @author Craig
*/
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.Border;
public class menu extends JPanel implements ActionListener{
JButton[][] grid;
TextField text = new TextField(20);
public menu(int width, int length) {
Border playerBorder = BorderFactory.createTitledBorder("Player");
Border comBorder = BorderFactory.createTitledBorder("Com");
JPanel player = new JPanel();
player.setBorder(playerBorder);// set border round player grid
player.setLayout(new GridLayout(4,4));
grid=new JButton[width][length]; //allocate the size of grid
for(int y=0; y<length; y++){
for(int x=0; x<width; x++){
grid[x][y]=new JButton(); //creates new button
player.add(grid[x][y]); //adds button to grid
grid[x][y].setBackground(Color.BLUE);//sets grid background colour
grid[x][y].setPreferredSize(new Dimension(40, 40));//sets each grid buttons dimensions
add(text);
grid[x][y].addActionListener(this);
}
}
JPanel com = new JPanel();
com.setBorder(comBorder);// set border round com grid
com.setLayout(new GridLayout(4,4));
grid=new JButton[width][length]; //allocate the size of grid
for(int y=0; y<length; y++){
for(int x=0; x<width; x++){
grid[x][y]=new JButton(); //creates new button
com.add(grid[x][y]); //adds button to grid
grid[x][y].setBackground(Color.BLUE);//sets grid background colour
grid[x][y].setPreferredSize(new Dimension(40, 40));//sets each grid buttons dimensions
}
}
//this.setLayout(new FlowLayout());
this.add(player);
this.add(com);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof JButton) {
JButton btn = (JButton)source;
text.setText("IN THE BOX ");
}
}
}
通過網格就循環就像你加入他們,並檢查電網[X] [Y]按鈕=='source' –
[這個問題](http://stackoverflow.com/q/21346281/877472)幾天前出現,我認爲這與你的情況非常相似(如果不是確切的話)。關於OP的解決方案是否合適存在一些爭議,但Trashgod的答案有很多很好的信息。最終,OP在其問題中的解決方案可能是解決問題的一種方法。 –
謝謝你會看看 – user3249467