简体   繁体   中英

java swing aligning radiobuttons

I want to center my radibuttons in the panel, but when I center it centers according to the lenght of the text of the button, so yes they are centered but not aligned each other and look very ugly. How can I fix my code?

radioButtonMenuPanel = new JPanel();
    radioButtonMenuPanel.setLayout(new BoxLayout(radioButtonMenuPanel,
            BoxLayout.PAGE_AXIS));

    ButtonGroup group = new ButtonGroup();
    for (String item : answerItems) {
        JRadioButton radioButton = new JRadioButton(item);
        radioButton.setAlignmentX(Component.Center_ALIGNMENT);
        radioButtonMenuPanel.add(radioButton);
        group.add(radioButton);
    }

You could always use a GridBagLayout . By using that layout, you can anchor the component in a grid in any side of the cell.

radioButtonMenuPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = GridBagConstraints.RELATIVE;
gbc.anchor = GridBagConstraints.WEST;

ButtonGroup group = new ButtonGroup();
for (String item : answerItems) {
    JRadioButton radioButton = new JRadioButton(item);
    group.add(radioButton);
    radioButtonMenuPanel.add(radioButton, gbc);
}

Something like that should work. By default a GridBagLayout centers the component in the screen in a small grid. In this case, we are just anchoring the component in the cell to the West where the component will be placed in the first column (gridx = 0), and for each radio button, it will position it next to the last component.

Hope that helped!

左对齐按钮到一个单独的面板,然后将该面板居中放置到另一个面板上,该如何做?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM