0

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

            }}

    }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
razshan
  • 1,128
  • 12
  • 41
  • 59

2 Answers2

0

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.

Michal Gruca
  • 522
  • 3
  • 6
0

It's hard to tell where your problem is from the code you have provided. However, if I take it at face value, it appears that your are reusing the field1 object rather than creating a new instance of JTextField upon every call to actionPerformed. If you change the code to something similar to :

field1 = new JTextField();
field1.setText(...)
...

your code should work as expected.

Kris Babic
  • 6,254
  • 1
  • 29
  • 18
  • then he will be left with one textfield recreated again and again – Michal Gruca Feb 28 '11 at 22:42
  • You wouldn't because the actionPerformed method already had the line of code: add(field1). Regardless of where the field1 variable was maintained, the action of creating new textfield and adding it to the container will work as expected. – Kris Babic Feb 28 '11 at 22:48
  • it's possible you need to invalidate the container. haven't tried tho. – MeBigFatGuy Feb 28 '11 at 23:58