我不確定如何解決此問題。當我使用它時,它運行良好,沒有錯誤,但是當我點擊其中一個按鈕時沒有輸入。 我使用JDK 1.7.1和Windows 7中的eclipse。 代碼基本上是創建3個按鈕,其中TextArea顯示每個按鈕單擊時的輸入。在事件中沒有顯示在JTextArea中的文本
public class Main implements ActionListener{
public JTextArea text;
public JButton b1;
public JButton b2;
public JButton b3;
public String choices[] = {"Rock", "Paper", "Scissors"};
public static void main(String[] args){
Main gui = new Main();
gui.go();
}
public void go(){
JFrame frame = new JFrame("Rock Paper Scissors");
text = new JTextArea(13,20);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JButton b1 = new JButton(choices[0]);
JButton b2 = new JButton(choices[1]);
JButton b3 = new JButton(choices[2]);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
text.setEditable(false);
JScrollPane scroller = new JScrollPane(text);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel1.add(scroller);
panel2.add(b1);
panel2.add(b2);
panel2.add(b3);
frame.getContentPane().add(BorderLayout.CENTER,panel1);
frame.getContentPane().add(BorderLayout.SOUTH, panel2);
frame.setSize(350,300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
text.setText("Your choice was" + choices[0]);
}
if (e.getSource() == b2) {
text.setText("Your choice was" + choices[1]);
}
if (e.getSource() == b3) {
text.setText("Your choice was" + choices[2]);
}
}
}
爲了澄清它是否不明顯,在方法內聲明'JButton b1'作爲局部變量隱藏'b1'作爲實例變量。 – Bruno
是的。我會將其添加到答案中。 – RoflcoptrException
謝謝。我現在明白它是如何工作的 – Streak324