java - 当我通过 if 语句单击 radioButton 时,颜色不会改变

标签 java

我的代码有什么问题吗?当我想通过单选按钮更改颜色时,它不会更改颜色。我放置的 if 语句对我来说很有意义,但它们没有注册背景以更改 setbackground 方法的颜色。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.event.ChangeListener;


public class GetTheColors extends JFrame
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGTH = 400;

JLabel label;
JPanel colorPanel;
JFrame frame;
JRadioButton redButton;
JRadioButton blueButton;
JRadioButton greenButton;
ActionListener listen;

public GetTheColors()
        {
            colorPanel = new JPanel();
            add(colorPanel, BorderLayout.CENTER);

            RadioButtons();
            setColor();

            setSize(FRAME_WIDTH,FRAME_HEIGTH);


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

public JPanel RadioButtons()
{
    redButton = new JRadioButton("red");
    redButton.addActionListener(listen);
    redButton.setSelected(true);

    greenButton = new JRadioButton("green");
    greenButton.addActionListener(listen);


    blueButton = new JRadioButton("blue");
    blueButton.addActionListener(listen);


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



    JPanel buttonPanel = new JPanel();
    buttonPanel.add(redButton);
    buttonPanel.add(greenButton);
    buttonPanel.add(blueButton);


    add(buttonPanel, BorderLayout.NORTH);
    return buttonPanel;
}
/**
 *
 */
public void setColor()
{
    if (redButton.isSelected()) 
    {
        colorPanel.setBackground(Color.red);
        colorPanel.repaint();
    }
    else if (blueButton.isSelected()) 
    {
        colorPanel.setBackground(Color.blue);
        colorPanel.repaint();
    }
    else if (greenButton.isSelected()) 
    {
        colorPanel.setBackground(Color.green);
        colorPanel.repaint();
    }

}

}

最佳答案

您需要初始化 ActionListener :

ActionListener listen = new ChoiceListener();

关于java - 当我通过 if 语句单击 radioButton 时,颜色不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33722246/

相关文章:

java - 如何将事件数据和事件名称从 Spring Boot 发送到 Angular?

java - 如何使用 split 方法查找 .txt 的 double 的两个特定列的平均值

使用 play dist 出现 java.io.FileNotFoundException

java:强相关的类对

java - 无法使用 Geronimo 检索 "entityManagerFactory"

java - MacOSX 升级后,Qualimap 中出现 "JAVA Parse Exception"错误

java - 在 Tomcat 上运行 GWT 应用程序时出现 StringIndexOutOfBoundsException 错误

java - .read ERROR : cannot find symbol symbol: method read(bufferedreader, <null>) 位置: jbutton 类型的变量 jtext1

java - Java 和 JS 中的 RegEx 行为不同?

java - spring接线接口(interface)时出现依赖不满足异常