Search code examples
javaswingjframejradiobutton

Creating JradioButton as user adds more items


I want to have this part in my application which allows user to add more options (in form of JradioButton). So by default I give some options to user in JradioButton and if they add more options (on the other part of the application); my Jframe should automatically add the options via Setup_Equipment_Frame method (shown Below) in which it gets array of strings that are basically the options that user added. I face some difficulties with it.


the code:


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

Now it actually works. I add the radio button however since the name of the added buttons are all "NewButton1", I can't have any control over them and I have access to only last created JRadioButton and the default ones. I don't know how many new options user might add.

My problem is how to automatically create JRadioButton with different names.

I apologies in advance if my question or code is confusing. I am not that experienced.

thanks


Update


thanks for the answers, with your help I solved the problem simply by adding an array of JradioButtons

For those who might face the same problem the code that works for me is as follow:

Solved:

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

     }

}

Thanks Alot


Solution

  • Now it actually works. I add the radio button however since the name of the added buttons are all "NewButton1", I can't have any control over them and I have access to only last created JRadioButton and the default ones. I don't know how many new options user might add.

    Not quite, and you may be confusing objects with variables. Understand that the JRadioButton objects have no name, no objects do, that yes they're created and then assigned to a local variable named NewButton1, that the variable's scope is limited to the for loop, and so regardless of the varialbe's name, it doesn't even exist outside of the for loop.

    Really your question boils down in essence to: how can I get a reference to a bunch of newly created objects, and there are several decent solutions including using an ArrayList of JRadioButton, and adding each button to the list. Or if you want to associate each JRadioButton with a String, then instead use a Map<String, JRadioButton>.

    As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.

    Here's an example that uses an ArrayList<JRadioButton>

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