Alpan67
Alpan67

Reputation: 105

Java Swing RadioButtons

i am making a group of radiobuttons and a Panel in the centre should change the colour clicking the radiobuttons.

Everything seems correct but ... it does not work ! With the main class i see the panel but the colour does not change ...

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;
}

Upvotes: 0

Views: 2710

Answers (3)

user2581154
user2581154

Reputation:

You can make while loop and Every time while loop will check which radioButton is selected

Upvotes: 0

christopher
christopher

Reputation: 27346

In your createButtonPanel() method, you should initialize your listener with:

listener = new ChoiceListener();    

There's no point creating a new ChoiceListener object when an ActionListener field exists.

Upvotes: 0

Arsen Alexanyan
Arsen Alexanyan

Reputation: 3141

Add in your constructor also initialization of ChoiceListener. listener = new ChoiceListener()

Upvotes: 1

Related Questions