0

我正在制作一组单选按钮,中心的面板应该更改单击单选按钮的颜色。

一切似乎都是正确的,但是......它不起作用!在主课上,我看到了面板,但颜色没有改变......

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

3 回答 3

1

在您的构造函数中添加ChoiceListener. listener = new ChoiceListener()

于 2013-02-25T18:12:11.290 回答
0

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

listener = new ChoiceListener();    

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

于 2013-02-25T18:14:24.660 回答
0

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

于 2013-02-25T18:16:46.950 回答