背景颜色和大小相等的 jradiobuttons

background color and equal sized jradiobuttons

我有三个单选按钮,其背景颜色如下所示。

我需要将它们全部拉伸到相同的大小,以便背景颜色统一(具有相同的宽度)。尝试添加 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);
}

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

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

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