【发布时间】:2014-01-30 05:05:06
【问题描述】:
我正在尝试使用 Java Swing 编写 Battleship 程序,目前我有一个制作两个网格的类。我正在尝试找出单击了哪个按钮的位置,以便以后可以使用它来放置镜头等...不幸的是,我遇到了很多麻烦。
我已经让对象通过使用 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 ");
}
}
}
【问题讨论】:
-
只需像添加它们一样遍历网格并检查 grid[x][y] button ==
source -
This question 几天前突然出现,我认为这与您的情况非常相似(如果不准确的话)。关于该OP的解决方案是否合适存在一些争论,但Trashgod的答案有很多很好的信息。最终,OP 在他们的问题中的解决方案可能是解决问题的一种方法。
-
谢谢看看
-
也可以考虑MVC。