2017-01-02 73 views
2

我正在創建一個基於井字遊戲的Tic Tac GUI遊戲,我正在努力使用2D數組與JOptionPane。到目前爲止,我已經能夠創建按鈕可供選擇:Java 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格式)。

希望我已經解釋過了。

回答

-1

希望,這將有助於

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

} 
} 
+0

對不起,我真的不明白這是如何工作! –

2
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方法,您必須重寫。