1

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);
}
Pradeep
  • 1,193
  • 6
  • 27
  • 44

2 Answers2

3

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);
camickr
  • 321,443
  • 19
  • 166
  • 288
  • Yes I was able to do it with GridLayout and a JPanel.Thank you. Is there any other shortcut?Because it's getting complicated as i keep adding components – Pradeep Jul 29 '15 at 16:17
  • @Pradeep, I find dividing the screeen into logicaly grouping of components is the easiest was to design the GUi. There are no shortcuts. – camickr Jul 29 '15 at 19:13
3

You can use a GridLayout(int rows, int cols):

    frame = new JFrame("Traffic Lights");
    frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
    JPanel panel = new JPanel( new GridLayout(3, 1) );
    frame.add(panel);

    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);
    panel.add(stop);
    panel.add(wait);
    panel.add(go);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setMinimumSize(new Dimension(300, 200));
    frame.pack();
    frame.setLocationRelativeTo(null);

For more infos see: GridLayout

JoGe
  • 872
  • 10
  • 26