I'm building a little app using Java and Swing in NetBeans. Using NetBeans design window, I created a JFrame with a JPanel inside.
Now I want to dynamically add some jTextFields to the JPanel. I wrote something like that:
Vector textFieldsVector = new Vector();
JTextField tf;
int i = 0;
while (i < 3) {
tf = new JTextField();
textFieldVector.add(tf);
myPanel.add(tf); //myPanel is the JPanel where I want to put the JTextFields
i++;
}
myPanel.validate();
myPanel.repaint();
But nothing happens: when I run the app, the JFrame shows with the JPanel inside, but the JTextFields don't.
I'm a total newbie in writing graphical Java apps, so I'm surely missing something very simple, but I can't see what.
In the Netbeans GUI, set the layout manager to something like GridLayout or FlowLayout (just for testing). You can do this by going to the GUI editor, clicking on your panel, and then right-clicking and selecting a layout.
Once you've changed to a different layout, go to the properties and alter the layout properties. For the GridLayout, you want to make sure you have 3 grid cells.
Instead of myPanel.validate(), try myPanel.revalidate().
The more canonical way to do this is to create a custom JPanel (without using the GUI editor) that sets its own layout manager, populates itself with components, etc. Then, in the Netbeans GUI editor, drag-and-drop that custom JPanel into the gui editor. Matisse is certainly capable of handling the runtime-modification of Swing components, but that's not the normal way to use it.