0

I have an java assignment in which I need to have the background color of a GUI change depending on user selected radio buttons listing different colors. My program has a JFrame to hold everything, then 3 JPanels (1 Instruction area, 1 Radio Button grid, 1 result Textfield) within that frame.

My action listener is currently setting the background color with this statement: getContentPane().setBackground(Color.decode(colorMap.get(btn.getName())));

The background for the JFrame and two of the three panels successfully changes to the correct color, but the panel holding the JRadioButtons will not change at all!

I have tried changing the opaque setting, I have tried setting the panel's background color to (0,0,0,0) but so far none of that is working for me. Does anyone have a suggestion of what I might try or read up on next?

I don't have enough reputation to post a picture but if seeing what I'm talking about helps, let me know and I can email you a screenshot.

Thanks!

mKorbel
  • 109,525
  • 20
  • 134
  • 319
SirChill88
  • 13
  • 1
  • 3

1 Answers1

4

You must additionally set all JRadioButtons.setOpaque(false).

Example with one JRadioButton opaque and one non-opaque:

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;


public class XFrame
    extends JFrame
{
    public XFrame(String title)
    {
        super(title);

        setDefaultCloseOperation(EXIT_ON_CLOSE);

        setLayout(new BorderLayout());

        JRadioButton b1 = new JRadioButton("Non opaque button");
        // button must not be opaque
        b1.setOpaque(false);

        // this button is opaque and does not use the background color of the frame
        JRadioButton b2 = new JRadioButton("Opaque button");

        JPanel p1 = new JPanel();
        // panel must be non opaque also
        p1.setOpaque(false);

        p1.setLayout(new BoxLayout(p1, BoxLayout.Y_AXIS));
        p1.add(b1);
        p1.add(b2);

        add(p1, BorderLayout.CENTER);

        getContentPane().setBackground(Color.red);

        setSize(200, 200);
    }

    public static void main(String[] args)
    {
        XFrame frame = new XFrame("Test");
        frame.setVisible(true);
    }

}
Uli
  • 1,390
  • 1
  • 14
  • 28
  • Thank you so much. I had tried something similar earlier but I created a JRadioButton[] array and was originally attempting to set the entire collection opaque. I moved the ".setOpaque(false)" into the for loop in which I was actually creating the buttons and that solved the problem! Now I need to play around with the color scheme because some of the dark colors hide the text. Thank you again! – SirChill88 Mar 06 '15 at 08:23