簡體   English   中英

Java Swing對齊單選按鈕

[英]java swing aligning radiobuttons

我想將單選按鈕居中放置在面板中,但是當我將其居中放置時,它會根據按鈕文本的長度居中放置,因此,是的,它們居中放置但彼此不對齊並且看上去非常難看。 如何修復我的代碼?

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

您可以始終使用GridBagLayout 通過使用該布局,您可以將組件錨定在單元格任何一側的網格中。

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

這樣的事情應該起作用。 默認情況下, GridBagLayout將組件在屏幕上的小網格中居中。 在這種情況下,我們只是將組件固定在單元格中的西部,該組件將被放置在第一列(gridx = 0)中,並且對於每個單選按鈕,它將定位在最后一個組件的旁邊。

希望能有所幫助!

左對齊按鈕到一個單獨的面板,然后將該面板居中放置到另一個面板上,該如何做?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM