【问题标题】:Creating JradioButton as user adds more items在用户添加更多项目时创建 JradioButton
【发布时间】:2015-09-03 23:18:07
【问题描述】:

我想在我的应用程序中包含这部分,它允许用户添加更多选项(以 JradioButton 的形式)。因此,默认情况下,我会在 JradioButton 中为用户提供一些选项,如果他们添加更多选项(在应用程序的另一部分);我的 Jframe 应该通过 Setup_Equipment_Frame 方法(如下所示)自动添加选项,在该方法中它获取字符串数组,这些字符串基本上是用户添加的选项。我面临一些困难。


代码:


public void Setup_Equipment_frame(String a[]) //String_Array of Newly added options
{

    //creating default options
    JRadioButton option1 = new JRadioButton("Visual Stadio");
    JRadioButton option2 = new JRadioButton("Netbeans");
    JRadioButton option3 = new JRadioButton("Eclipse");

   //Creating the button group
    ButtonGroup group = new ButtonGroup();
    group.add(option1);
    group.add(option2);
    group.add(option3);

   //setting the frame layout
    setLayout(new FlowLayout());

   for(int i=0; i<=a.length-1;i++) //loop for how many new options are added
    {
        if(a[i] != null) //if the array's current item is not null 
           {
        JRadioButton NewButton1= new JRadioButton(""+a[i]); //Add the Button
        add(NewButton1);
           }
    }
  //adding the default options
    add(option1);
    add(option2);
    add(option3);

    pack();
}

现在它确实有效。我添加了单选按钮,但是由于添加的按钮的名称都是“NewButton1”,我无法控制它们,我只能访问最后创建的 JRadioButton 和默认按钮。 我不知道用户可能会添加多少新选项。

我的问题是如何自动创建不同名称的 JRadioButton。

如果我的问题或代码令人困惑,我提前道歉。我没那么有经验。

谢谢


更新


感谢您的回答,在您的帮助下,我只需添加一个 JradioButtons 数组即可解决问题

对于那些可能面临同样问题的人,适用于我的代码如下:

已解决:

   public void Setup_Equipment_frame(String a[])
{
    int number_of_options=1;//number of new options
 for(int i=0; i<=a.length-1;i++)
    {
        if(a[i] != null){
        number_of_options++;
       }
    }
    JRadioButton []v=new JRadioButton[number_of_options];
     setLayout(new FlowLayout());
    for(int z=0; z<=number_of_options-1;z++)
    {if(a[z] != null){
        {
            v[z]=new JRadioButton(a[z]);
            add(v[z]);
        }
    }

     }

}

非常感谢

【问题讨论】:

    标签: java swing jframe jradiobutton


    【解决方案1】:

    现在它确实有效。我添加了单选按钮,但是由于添加的按钮的名称都是“NewButton1”,我无法控制它们,我只能访问最后创建的 JRadioButton 和默认按钮。我不知道用户可能会添加多少新选项。

    不完全是,您可能会将 objectsvariables 混淆。了解 JRadioButton objects 没有名称,没有任何对象,是的,它们被创建然后分配给名为 NewButton1 的 local 变量,该变量的范围仅限于for 循环,因此无论变量的名称如何,它甚至都不存在于 for 循环之外。

    实际上,您的问题本质上归结为:我如何获得参考 一堆新创建的对象,并且有几个不错的解决方案,包括使用 JRadioButton 的 ArrayList,并将每个按钮添加到列表中。或者,如果您想将每个 JRadioButton 与一个字符串相关联,那么请改用 Map&lt;String, JRadioButton&gt;

    顺便说一句,你会想学习和使用Java naming conventions。变量名应全部以小写字母开头,而类名应以大写字母开头。学习这一点并遵循这一点将使我们能够更好地理解您的代码,并让您更好地理解其他人的代码。

    这是一个使用ArrayList&lt;JRadioButton&gt;的示例

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class AddRadioButtons extends JPanel {
        private static final int PREF_W = 300;
        private static final int PREF_H = 400;
    
        // List that holds all added JRadioButtons
        private List<JRadioButton> radioButtonList = new ArrayList<>();
    
        // jpanel to hold radiobuttons in a verticle grid
        private JPanel buttonPanel = new JPanel(new GridLayout(0, 1)); 
        private JTextField radioBtnNameField = new JTextField(10);
    
        public AddRadioButtons() {
            // jpanel to add to jscrollpane
            // nesting JPanels so that JRadioButtons don't spread out inside the scrollpane.
            JPanel innerViewPanel = new JPanel(new BorderLayout());
            innerViewPanel.add(buttonPanel, BorderLayout.PAGE_START);
            JScrollPane scrollPane = new JScrollPane(innerViewPanel);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    
            // holds textfield and button for adding new radiobuttons
            JPanel topPanel = new JPanel();
            topPanel.add(radioBtnNameField);
            Action addRBtnAction = new AddRadioBtnAction("Add Radio Button");
            topPanel.add(new JButton(addRBtnAction));
            radioBtnNameField.setAction(addRBtnAction);
    
            // holds button to display selected radiobuttons
            JPanel bottomPanel = new JPanel();
            bottomPanel.add(new JButton(new PrintAllSelectedBtnAction("Print All Selected Buttons")));
    
            setLayout(new BorderLayout());
            add(scrollPane, BorderLayout.CENTER);
            add(topPanel, BorderLayout.PAGE_START);
            add(bottomPanel, BorderLayout.PAGE_END);
        }
    
        @Override
        public Dimension getPreferredSize() {
            if (isPreferredSizeSet()) {
                return super.getPreferredSize();
            }
            return new Dimension(PREF_W, PREF_H);
        }
    
        // I prefer to use AbstractAction in place of ActionListeners since
        // they have a little more flexibility and power.
        private class AddRadioBtnAction extends AbstractAction {
            public AddRadioBtnAction(String name) {
                super(name);
                int mnemonic = (int) name.charAt(0);
                putValue(MNEMONIC_KEY, mnemonic);
            }
    
            @Override
            public void actionPerformed(ActionEvent evt) {
                String text = radioBtnNameField.getText();
                JRadioButton rbtn = new JRadioButton(text);
                radioButtonList.add(rbtn);
                buttonPanel.add(rbtn);
                buttonPanel.revalidate();
                buttonPanel.repaint();
    
                radioBtnNameField.selectAll();
            }
        }
    
        private class PrintAllSelectedBtnAction extends AbstractAction {
            public PrintAllSelectedBtnAction(String name) {
                super(name);
                int mnemonic = (int) name.charAt(0);
                putValue(MNEMONIC_KEY, mnemonic);
            }
    
            @Override
            public void actionPerformed(ActionEvent e) {
                for (JRadioButton radioBtn : radioButtonList) {
                    if (radioBtn.isSelected()) {
                        System.out.println(radioBtn.getActionCommand() + " is selected");
                    }
                }
                System.out.println();
            }
        }
    
        private static void createAndShowGui() {
            AddRadioButtons mainPanel = new AddRadioButtons();
    
            JFrame frame = new JFrame("Add Radio Buttons");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.getContentPane().add(mainPanel);
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            // run the Swing code in a thread-safe manner
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGui();
                }
            });
        }
    }
    

    【讨论】:

    • 感谢您的好回答...我会检查命名约定。实际上,另一个答案对我有所帮助,现在我解决了这个问题。我只是简单地使用了一组 JradioButtons,它工作得很好。再次感谢您,先生。
    • 我使用了你所说的地图,它也非常好用。再次感谢您的精彩回答。
    • @HiradGorgoroth:请查看使用 JRadioButton 的 ArrayList 的示例代码,我可能会这样做。
    【解决方案2】:

    您只需要声明一个 JRadioButton 数组,然后您将从用户那里获取数组的大小。然后通过循环将它们添加到面板中。我想这就是你要问的,如果不是然后告诉我。

    【讨论】:

    • 哦,例如,如果我想创建 4 个单选按钮,我应该使用这样的东西: JRadioButton []v=new JRadioButton[4];如果我这样做,我可以通过 if(v[1].isSelected()) 来检查它们吗?
    • if(v[1].isSelected()) 通过这个你
    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 2011-09-20
    • 2018-03-23
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    相关资源
    最近更新 更多