2016-04-29 100 views
-1

我正在學習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。我不知道這意味着什麼,所以我不知道如何解決這個問題。

+0

嘗試在將它們添加到組之前實例化單選按鈕。 – Zymus

+0

這不是一個問題,但謝謝你指出這一點! –

+0

請改善您的問題標題。應該有信息,總結你的*問題*而不是你的*困境*。假設你的代碼不適合從一開始。 –

回答

4

您已聲明兩次相同的變量。如果在全局和本地範圍內聲明相同的變量(JTextArea tb),它將是一個單獨的對象。從Screen()構造函數中刪除本地作用域中的聲明,以便它可以工作。 嘗試這種

tb = new JTextArea("Text Area"); 

代替

JTextArea tb = new JTextArea("Text Area"); 

因爲你當前的代碼,tb仍然沒有在全球範圍內進行初始化。

+0

我覺得自己像個白癡!非常感謝!檢查我什麼時候可以! –

相關問題