Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a program automatically add text fields in java [closed]

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.

like image 620
Ikspeto Avatar asked Jan 19 '12 15:01

Ikspeto


People also ask

What is the difference between JTextField and JTextArea?

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.

What is JDialog in Java?

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.


1 Answers

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);
            }
        });
    }
}
like image 74
Eng.Fouad Avatar answered Oct 23 '22 10:10

Eng.Fouad