我正在用Java创建基于Tic Tac Toe GUI的游戏,并且正在努力将2D数组与JOptionPane
结合使用。到目前为止,我已经能够创建按钮以供选择:
import java.awt.GridLayout;
import javax.swing.*;
public class YourHEad {
public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout Test");
frame.setLayout(new GridLayout(4, 4));
StringBuilder sb = new StringBuilder();
sb.append("<html>");
String[][] seats = new String [4][4];
String alpha = "ABCD";
for (int i=0; i<4; i++){
String letter = Character.toString(alpha.charAt(i));
for (int j=0; j<4; j++){
String number = Integer.toString(j+1);
seats [i][j]=letter+number+" ";
}
}
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
frame.add(new JButton(seats[i][j]));
}
}
frame.pack();
frame.setVisible(true);
if(new JButton(seats[0][0]).getModel().isPressed()){
System.out.println("the button is pressed");
}
}}
从最后几行代码中您可以看到,我正在尝试弄清楚如何知道何时按下了按钮,例如,如果用户单击“ A1”(因此单击0,0),则该程序可以输出文本(我将其更改为JOptionPane格式)。
希望我已经解释清楚了。
最佳答案
希望,这会有所帮助
public class YourHEad
{
public static void main(String[] args)
{
final JFrame frame = new JFrame("GridLayout Test");
frame.setLayout(new GridLayout(4, 4));
StringBuilder sb = new StringBuilder();
sb.append("<html>");
String[][] seats = new String [4][4];
String alpha = "ABCD";
for (int i=0; i<4; i++){
String letter = Character.toString(alpha.charAt(i));
for (int j=0; j<4; j++){
String number = Integer.toString(j+1);
seats [i][j]=letter+number+" ";
}
}
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
JButton button= new JButton(seats[i][j]);
button.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
JOptionPane.showMessageDialog(frame, ((JButton)(e.getSource())).getText()+" is Pressed");
}
});
frame.add(button);
}
}
frame.pack();
frame.setVisible(true);
}
}