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.
The main difference between JTextField and JTextArea in Java is that a JTextField allows entering a single line of text in a GUI application while the JTextArea allows entering multiple lines of text in a GUI application.
JDialog is a part Java swing package. The main purpose of the dialog is to add components to it. JDialog can be customized according to user need . Constructor of the class are: JDialog() : creates an empty dialog without any title or any specified owner.
Here is an example using Box:

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);
            }
        });
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With