我正在尝试使用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