Search code examples
javaswingbackgroundlayout-managerjradiobutton

background color and equal sized jradiobuttons


I have three radio buttons with background colors as shown below. enter image description here

I need to stretch all of them to same size so that the background colors are uniform(with same width).Tried adding setWidth(Dimension d) but it's not working.

public class TrafficLights {
JFrame frame;
JRadioButton stop,go,wait;
JTextField signal;
ButtonGroup grp;
Dimension dim = new Dimension(200,30);
public TrafficLights(){
    frame = new JFrame("Traffic Lights");
    frame.setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
    stop = new JRadioButton("Red");
    stop.setBackground(Color.RED);
    stop.setSize(dim);      

    wait = new JRadioButton("Orange");
    wait.setBackground(Color.ORANGE);
    wait.setSize(dim);

    go = new JRadioButton("Green");
    go.setBackground(Color.GREEN);
    go.setSize(dim);

    grp = new ButtonGroup();
    grp.add(stop);grp.add(wait);grp.add(go);
    frame.getContentPane().add(stop);
    frame.getContentPane().add(wait);
    frame.getContentPane().add(go);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setMinimumSize(new Dimension(300,200));
    frame.pack();
    frame.setLocationRelativeTo(null);
}

Solution

  • Use a JPanel with a GridLayout, then add the buttons to the panel and the the panel to the frame:

    JPanel panel = new JPanel( new GridLayout(0, 1) );
    panel.add(button1);
    ...
    frame.add(panel, BorderLayout.PAGE_START);