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();
}
}
照顧java命名converntion。變量名稱應該以小寫字符開頭 – Jens