背景颜色和大小相等的jradiobuttons

时间:2015-07-29 15:35:35

标签: java swing background layout-manager jradiobutton

我有三个带背景颜色的单选按钮,如下所示。 enter image description here

我需要将它们全部拉伸到相同的大小,以便背景颜色均匀(宽度相同)。添加setWidth(Dimension d)但它不起作用。

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

2 个答案:

答案 0 :(得分:3)

JPanelGridLayout一起使用,然后将按钮添加到面板,将面板添加到框架中:

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

答案 1 :(得分:3)

您可以使用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);

有关更多信息,请参阅:GridLayout