Java Swing单选按钮

Java Swing单选按钮,java,swing,Java,Swing,我正在制作一组单选按钮,中间的一个面板应通过单击单选按钮来更改颜色 一切似乎都是正确的,但。。。它不起作用! 对于主类,我看到了面板,但颜色没有改变 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ChoiceFrame extends JFrame { public ChoiceFrame() { class ChoiceListener impl

我正在制作一组单选按钮,中间的一个面板应通过单击单选按钮来更改颜色

一切似乎都是正确的,但。。。它不起作用! 对于主类,我看到了面板,但颜色没有改变

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()

在createButtonPanel()方法中,应使用以下命令初始化侦听器:

listener = new ChoiceListener();    

当ActionListener字段存在时,创建新的ChoiceListener对象没有意义。

您可以在
while
循环,每次
while
循环都会检查选中了哪个单选按钮

您在哪里初始化了侦听器?您如何在构造函数中声明类?是否创建choiceListener的新实例?使用内部定义的“actionPerformed”实例化匿名内部类,如“listener=new ActionListener()”,更改该类的“声明”。Thx是缺少的部分。。。