2017-08-30 49 views
0

這是使用Java製作tictactoe遊戲的第一步。我想單擊按鈕1打印編號1,但它不起作用

我想打印數字1,當點擊按鈕1.有9個按鈕,但它不工作是什麼錯我打印e.getsource方法和B1按鈕,他們是不一樣的。這是爲什麼發生?

package tictactoe; 

import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class TicTacToe implements ActionListener{ 

JFrame frame1; 
JButton B1 = new JButton(); 
JButton B2 = new JButton(); 
JButton B3 = new JButton(); 
JButton B4 = new JButton(); 
JButton B5 = new JButton(); 
JButton B6 = new JButton(); 
JButton B7 = new JButton(); 
JButton B8 = new JButton(); 
JButton B9 = new JButton(); 

public void createGui(){ 
    frame1 = new JFrame(); 
    frame1.setTitle("TicTacToe"); 
    frame1.setSize(600, 600); 
    frame1.setLayout(new GridLayout(3,3,0,0)); 
    frame1.setLocationRelativeTo(null); 

    frame1.add(B1); 
    frame1.add(B2); 
    frame1.add(B3); 
    frame1.add(B4); 
    frame1.add(B5); 
    frame1.add(B6); 
    frame1.add(B7); 
    frame1.add(B8); 
    frame1.add(B9); 

    TicTacToe A1 = new TicTacToe(); 

    B1.addActionListener(A1); 
    B2.addActionListener(A1); 
    B3.addActionListener(A1); 
    B4.addActionListener(A1); 
    B5.addActionListener(A1); 
    B6.addActionListener(A1); 
    B7.addActionListener(A1); 
    B8.addActionListener(A1); 
    B9.addActionListener(A1); 

    // frame1.pack(); 
    frame1.setVisible(true); 
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} 

public void actionPerformed(ActionEvent e) { 
    if(e.getSource()==B1){ 
     B1.setText("1"); 
    } 
} 

public static void main(String[] args) { 
    TicTacToe T1 = new TicTacToe(); 
    T1.createGui(); 
} 
} 
+1

照顧java命名converntion。變量名稱應該以小寫字符開頭 – Jens

回答

2

的理由讓你的程序不起作用是您創建作爲參數傳遞給JButton.addActionListener()使用新的井字遊戲。嘗試使用this,並刪除A1

B2.addActionListener(this); 

然後它會工作。

但是我有一個不同的方法比使用JButton.addActionListener()建議。

相反,您可以使用以Action作爲參數的構造函數JButton。實施您自己的Action,它擴展了AbstractAction,然後在需要實施的actionPerformed()方法中設置文本。 您可以讓Action爲您按下時想要寫入的文字帶參數。

private class PressedAction extends AbstractAction { 
    private final String text; 

    public PressedAction(String text) { 
     this.text = text; 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     ((JButton) e.getSource()).setText(text); 
    } 
} 
相關問題