[英]I do not understand why this code won't work(new to 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);
}
}
这是屏幕类:
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
。 我不知道这意味着什么,所以我不知道如何解决此问题。
您已经声明了两次相同的变量。 如果在全局和局部范围内声明相同的变量( JTextArea tb
),它将是一个单独的对象。 从Screen()
构造函数中删除本地作用域中的声明,这样它将起作用。 尝试这个
tb = new JTextArea("Text Area");
代替
JTextArea tb = new JTextArea("Text Area");
由于您当前的代码,因此tb
仍未在全局范围内初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.