java 如何在循环中将JRadioButton添加到JPane

bkhjykvo  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(142)

下面的代码:

public class PnlMenuRadioButtons extends JPanel {

    public PnlMenuRadioButtons(String menuName) {
        super();
        setLayout(new BorderLayout());
        Font radioButtonsFont = new Font("Arial", Font.PLAIN, 14);
        JPanel titlePanel = new JPanel();
        titlePanel.setLayout(new BorderLayout());
        titlePanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        add(titlePanel, BorderLayout.NORTH);
        Font menuTitleFont = new Font("Tempus Sans ITC", Font.BOLD, 16);
        JLabel lblMenu = new JLabel(menuName);
        lblMenu.setFont(menuTitleFont);
        titlePanel.add(lblMenu, BorderLayout.WEST);
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        add(contentPanel, BorderLayout.CENTER);
        /*
        //VERSION 1
        //FROM HERE
        ButtonGroup btngrp = new ButtonGroup();
        JRadioButton rdbtn = new JRadioButton("hi");
        btngrp.add(rdbtn);
        contentPanel.add(rdbtn);
        JRadioButton rdbtn2 = new JRadioButton("hello");
        btngrp.add(rdbtn2);
        contentPanel.add(rdbtn2);
        //TO HERE
        */
        //VERSION 2
        //FROM HERE
        String[] strs = {"hi", "hello"};
        ButtonGroup radioButtonsGroup = new ButtonGroup();
        for(int i = 0; i < 2; i++) {
            JRadioButton rdbtn = new JRadioButton((String)Array.get(strs, i));
            rdbtn.setFont(radioButtonsFont);
            radioButtonsGroup.add(rdbtn);
            contentPanel.add(rdbtn);
        }
        //TO HERE
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
        add(buttonPanel, BorderLayout.SOUTH);
        Font buttonFont = new Font("Arial", Font.PLAIN, 14);
        JButton btnBack = new JButton("Back");
        btnBack.setFont(buttonFont);
        btnBack.setActionCommand("Back");
        buttonPanel.add(btnBack);
        JButton btnGO = new JButton("Go");
        btnGO.setFont(buttonFont);
        btnGO.setActionCommand("Go");
        buttonPanel.add(btnGO);
    }
}

如果我使用版本1,contentPanel会正确添加JRadioButton
但是我想要一个循环,因为我想用用户选择的JRadioButton的数量来改变代码,所以它将是随机的。
但是如果我使用版本2,似乎contentPanel从来没有添加JRadioButton。我错过了什么?
谢谢。

2ic8powd

2ic8powd1#

您的代码末尾缺少一个}。请尝试为contentPanel添加不同的变量名。add(),可能是这样。

相关问题