How to remove components from jpanel. In the below code, textfields are created depending on the val. This is working fine for creating. But when the value is lowered in the spinner, the textfield should also get reduced.
i tried to remove all the components from array txtField and did not work.
int val = (int) textFieldGen.getModel().getValue(); //getting the value from JSpinner
JTextField[] txtField = new JTextField[val];
//tried panel.revalidate(); panel.repaint();
//removing elements if exists. gives null pointer exception.
try {
for (JTextField txtComp : txtField) {
panel.remove(txtComp);
}
} catch (Exception ex) {
System.out.println(ex);
}
panel.revalidate();
panel.repaint();
//creating
int row = 1;
for (int i = 0; i < txtField.length; i++) {
row++;
layout.appendRow(RowSpec.decode("30px"));
txtField[i] = new JTextField(10);
panel.add(txt[i], cc.xy(4, row));
}
panel.revalidate();
panel.repaint();