2013-02-25 55 views
0

我正在製作一組單選按鈕,並且中央的Panel應該更改點按單選按鈕的顏色。Java Swing RadioButtons

一切似乎都正確,但...它不起作用! 隨着主類我看到面板,但是顏色不會改變......

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class ChoiceFrame extends JFrame 
{ 
    public ChoiceFrame() 
    { 

     class ChoiceListener implements ActionListener 
     { 
      public void actionPerformed(ActionEvent event) 
      { 
       setTheColor(); 
      } 
     } 

     buttonPanel = createButtonPanel(); 
     add(buttonPanel, BorderLayout.SOUTH); 
     colorPanel = createColorPanel(); 
     add(colorPanel, BorderLayout.NORTH); 
     setSize(FRAME_WIDTH, FRAME_HEIGHT); 
     colorPanel.repaint(); 
    } 


    public JPanel createButtonPanel() 
    { 
     JPanel panel = new JPanel(); 
     panel.setLayout(new GridLayout(3,1)); 

     redButton = new JRadioButton("Red Colour"); 
     blueButton = new JRadioButton("Blue Colour"); 
     greenButton = new JRadioButton("Green Colour"); 

     redButton.addActionListener(listener); 
     blueButton.addActionListener(listener); 
     greenButton.addActionListener(listener); 

     ButtonGroup group = new ButtonGroup(); 
     group.add(redButton); 
     group.add(blueButton); 
     group.add(greenButton); 

     panel.add(redButton); 
     panel.add(blueButton); 
     panel.add(greenButton); 

     return panel; 
    } 

    public JPanel createColorPanel() 
    { 
     JPanel panel = new JPanel(); 
     return panel; 
    } 


    public void setTheColor() 
    { 
     if (redButton.isSelected()) 
      colorPanel.setBackground(Color.RED); 
     else if (blueButton.isSelected()) 
      colorPanel.setBackground(Color.BLUE); 
     else if (greenButton.isSelected()) 
      colorPanel.setBackground(Color.GREEN); 
    } 


    private JPanel colorPanel; 
    private JPanel buttonPanel; 

    private JRadioButton redButton; 
    private JRadioButton blueButton; 
    private JRadioButton greenButton; 

    private ActionListener listener; 

    private static final int FRAME_WIDTH = 400; 
    private static final int FRAME_HEIGHT = 400; 
} 
+4

你在哪裏初始化監聽器?你如何設法在構造函數中聲明類? – skuntsel 2013-02-25 18:11:27

+0

你是否創建了choiceListener的新實例? – christopher 2013-02-25 18:11:30

+0

用你的'actionPerformed'內部定義的'listener = new ActionListener()'實例化匿名內部類來更改該類'聲明'。 – skuntsel 2013-02-25 18:16:44

回答

1

添加在你的構造也ChoiceListener初始化。

listener = new ChoiceListener();  

沒有意義,創建一個新的ChoiceListener對象時一個ActionListener字段存在: listener = new ChoiceListener()

+0

是thx那是錯誤的 – Alpan67 2013-02-25 18:18:00

0

在你createButtonPanel()方法,你應該初始化監聽器。

0

您可以while循環,每次循環while將檢查其單選按鈕選擇