Make program automatically add text fields in java

Maybe there is a similar question, but I could not find it.

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

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

Thanks in advance.

+4
source share
2 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); } }); } } 
+6
source

Source: https://habr.com/ru/post/1391874/


All Articles