Java JOptionPane



我正在用Java创建一个基于井字游戏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 格式)。

希望我已经解释好了。

for (int i = 0; i < 4; i++){
    for (int j = 0; j < 4; j++){
        JButton jb = new JButton(seats[i][j]);
        jb.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(((JButton)(e.getSource())).getText());
            }
        });
        frame.add(jb);
    }
}

在 Java 中,您可以使用 ActionListeners .添加侦听器后,它将侦听操作,当执行操作时,它会调用您必须重写#actionPerformed方法。

希望,这会有所帮助

 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);
}
}

最新更新