Java Swing RadioButtons

2020年9月10日 42点热度 0条评论 来源: Alpan67

我正在制作一组单选按钮,并且中央的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; 
} 


===========解决方案如下:

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

listener = new ChoiceListener();  

没有意义,创建一个新的ChoiceListener对象时一个ActionListener字段存在: listener = new ChoiceListener()

    原文作者:Alpan67
    原文地址: https://stackoverflow.com/q/15073477
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。