Java- How to add more textfields by clicking a button?

无人久伴 提交于 2019-12-04 19:17:59

It would be wise that instead of adding components to your JFrame directly, you add them to a JPanel. Though related to your problem, have a look at this small example, hopefully might be able to give you some hint, else ask me what is out of bounds.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JFrameExample
{   
    private JFrame frame;
    private JButton button;
    private JTextField tfield;
    private String nameTField;
    private int count;

    public JFrameExample()
    {
        nameTField = "tField";
        count = 0;
    }

    private void displayGUI()
    {
        frame = new JFrame("JFrame Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout(0, 1, 2, 2));
        button = new JButton("Add JTextField");
        button.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                tfield = new JTextField();
                tfield.setName(nameTField + count);
                count++;
                frame.add(tfield);
                frame.revalidate();  // For JDK 1.7 or above.
                //frame.getContentPane().revalidate(); // For JDK 1.6 or below.
                frame.repaint();
            }
        });
        frame.add(button);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new JFrameExample().displayGUI();
            }
        });
    }
}

Supposing that you have a main container called panel and a button variable button which is already added to panel, you can do:

// handle the button action event
button.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    // create the new text field
    JTextField newTextField = new JTextField();
    // add it to the container
    panel.add(newTextField);
    panel.validate();
    panel.repaint();
  }
});

When adding the new text field, you may need to mention some layout related characteristics, depending on the layout manager you are using (for instance if you use GridBagLayout, you will need to specify the constraints).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!