Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding JTextField to a JPanel and showing them

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.

like image 512
Davide Gualano Avatar asked Feb 13 '09 14:02

Davide Gualano


2 Answers

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.

like image 59
James Schek Avatar answered Oct 12 '22 23:10

James Schek


It's been a while since I've done some Swing but I think you'll need to recall pack() to tell the frame to relayout its components

EDIT: Yep, I knew it had been too long since I did Swing. I've knocked up the following code which works as expected though and adds the textfields...

    JFrame frame = new JFrame("My Frame");
    frame.setSize(640, 480);
    JPanel panel = new JPanel();
    panel.add(new JLabel("Hello"));
    frame.add(panel);
    frame.setLayout(new GridLayout());
    frame.pack();
    frame.setVisible(true);
    Vector textFieldVector = new Vector();
    JTextField tf;
    int i = 0;
    while (i < 3) {
        tf = new JTextField();
        textFieldVector.add(tf);
        panel.add(tf); //myPanel is the JPanel where I want to put the JTextFields
        i++;
    }
    panel.validate();
    panel.repaint();
like image 2
tddmonkey Avatar answered Oct 13 '22 00:10

tddmonkey