首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java Swing RadioButtons

Java Swing RadioButtons
EN

Stack Overflow用户
提问于 2013-02-26 02:08:12
回答 3查看 2.7K关注 0票数 0

我正在制作一组单选按钮,中间的一个面板单击单选按钮会改变颜色。

一切看起来都是对的,但是...它不起作用!在主类中,我看到了面板,但颜色没有改变……

代码语言:javascript
复制
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;
}
EN

回答 3

Stack Overflow用户

发布于 2013-02-26 02:12:11

在你的构造函数中添加ChoiceListener的初始化。listener = new ChoiceListener()

票数 1
EN

Stack Overflow用户

发布于 2013-02-26 02:14:25

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

代码语言:javascript
复制
listener = new ChoiceListener();    

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

票数 0
EN

Stack Overflow用户

发布于 2013-02-26 02:16:47

您可以创建while循环,每次while循环都会检查选择了哪个radioButton

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15073477

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档