Search code examples
javaswingjtextfield

Adding multiple JTextFields under one ActionListener?


I am working with JTextFields, JComboBox, and buttons. When I select some information from JComboBox, I press the button. That creates a JTextField. and sets the text of the JTextField by using the getSelectedItem().toString() method.

The issue I am facing is that I want to 'add' multiple JTextFields as the user desires. So if user clicks the button 3 times, I want 3 new JTextFields. As of now, the JTextField gets overwrite.

        public AdjustmentForm() //constructor begins, method for embedded main class
        {


        setTitle("Other Therapy Options");
        setSize(620, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        setLayout(new FlowLayout(FlowLayout.LEFT));


 String[] fluids = { "      ", "Normal Saline", "Albumin", "23.5% NaCl","3% NaCl", "pRBC"}; 
 String[] volume = { "      ", "30", "50", "100", "500", "1000", "other"};

fluidsList = new JComboBox(fluids); 
volumeList = new JComboBox(volume); 

...
...

        thehandler handler = new thehandler();
        button1.addActionListener(handler);
        }

            private class thehandler implements ActionListener{
            public void actionPerformed(ActionEvent event){

            setSize(620, 401);
            field1.setText(" "+fluidsList.getSelectedItem().toString()+", " +volumeList.getSelectedItem().toString() + " ml ");

        add(field1);

            }}

    }

Solution

  • In your actionlistener just call container.add(new JtextField("Param"));

    That will add multiple JTextfields. After that take care about your layout. I haven't worked with layouts for a while so I won't comment on that.