我正在學習JRadioButtons
,我不知道它爲什麼在我正在觀看的教程中工作,而不是在我的代碼中。有人可以看看嗎?我不明白爲什麼這段代碼不起作用(新到JRadioButtons)
主類:
import java.awt.*;
import javax.swing.*;
public class Calculator extends JPanel{
private static final long serialVersionUID = 1L;
public static void main(String[] args){
Screen screen = new Screen();
screen.setVisible(true);
}
}
這裏是Screen類:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class Screen extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
JRadioButton b1, b2;
ButtonGroup group;
JTextArea tb;
public Screen(){
super("First GUI");
setSize(600,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel p1 = new JPanel();
JTextArea tb = new JTextArea("Text Area");
group = new ButtonGroup();
group.add(b1);
group.add(b2);
b1 = new JRadioButton("Hello");
b1.setActionCommand("HELLO!");
b1.addActionListener(this);
b2 = new JRadioButton("Goodbye");
b2.setActionCommand("Goodbye! =)");
b2.addActionListener(this);
p1.add(b1);
p1.add(b2);
p1.add(tb);
add(p1);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
tb.setText(e.getActionCommand());
}
}
在我的新的Java頭這應該很好地工作。我初始化按鈕,初始化組。我點擊其中一個按鈕後出現錯誤:AWT-EventQueue-0
。我不知道這意味着什麼,所以我不知道如何解決這個問題。
嘗試在將它們添加到組之前實例化單選按鈕。 – Zymus
這不是一個問題,但謝謝你指出這一點! –
請改善您的問題標題。應該有信息,總結你的*問題*而不是你的*困境*。假設你的代碼不適合從一開始。 –