Make a program automatically add text fields in java

Ikspeto picture Ikspeto · Jan 19, 2012 · Viewed 7.8k times · Source

Maybe there is a similar question to this, but I couldn't find a one.

Id like my program ( awt or swing ) to add controls ( like text fields ) automatically.

For example : A dialog program has 10 fields for inputting names, but I need 11 so by pressing a button a new field will appear.

Thank you in advance.

Answer

Eng.Fouad picture Eng.Fouad · Jan 19, 2012

Here is an example using Box:

enter image description here

import java.awt.BorderLayout;
import java.awt.event.*;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class MultiJComponentsTest extends JFrame
{
    private JButton btnAdd;
    private JPanel centerPanel;
    private Box vBox;

    public MultiJComponentsTest()
    {
        super("The Title");
        btnAdd = new JButton("Add new JTextField!");
        btnAdd.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e)
            {
                vBox.add(new JTextField(20));
                pack();
            }

        });
        vBox = Box.createVerticalBox();
        centerPanel = new JPanel();
        JPanel contentPanel = (JPanel) getContentPane();
        contentPanel.setLayout(new BorderLayout());
        contentPanel.add(btnAdd, "South");
        contentPanel.add(centerPanel, "Center");
        centerPanel.add(vBox);
        pack();
    }

    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new MultiJComponentsTest().setVisible(true);
            }
        });
    }
}