[英]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.