0

I want to add and remove JTextField controls dynamically using a combo box.

I have a combo box from 1 to 10. For example I press 3 to add 3 text field it works great. But when I press a second time (2) I want to delete the last text field.

This is my code:

LineBorder a =new javax.swing.border.LineBorder(Color.black);
String g =(String) nbparam.getSelectedItem();
int x = Integer.parseInt(g);
for(int i=0;i<x;i++){
    c=new JTextField();
    c.setText("Paramètre"+(i+1));
    c.setBorder(a);
    c.setSize(200, 28);
    c.setLocation(30,20+43*i);
    jPanel3.add(c);
    jPanel3.revalidate();
    jPanel3.repaint();
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Ncib Sami
  • 5
  • 3
  • Before you add anything simply call `jPanel3.removeAll()`. This statements deletes all elements, you're added before. – Sergiy Medvynskyy Mar 10 '20 at 15:11
  • thank you very much it works – Ncib Sami Mar 10 '20 at 15:25
  • 1) `c.setSize(200, 28);` That's no better than a guess. Set a number of columns then allow the layout manager to do its job. 2) `c.setLocation(30,20+43*i);` Ugh.. Use a `FlowLayout`. More generally: Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Mar 10 '20 at 16:00
  • .. 3) `String g =(String) nbparam.getSelectedItem(); int x = Integer.parseInt(g);` Better something like: `int x = nbparam.getSelectedIndex() + 1;` – Andrew Thompson Mar 10 '20 at 16:02
  • Does this answer your question? [Value Change Listener to JTextField](https://stackoverflow.com/questions/3953208/value-change-listener-to-jtextfield) – Rodrigo Mar 10 '20 at 21:30

0 Answers0