我想在单击按钮“添加”时添加文本字段。但这是行不通的。帮我

时间:2020-07-09 16:22:52

标签: javascript eclipse swing user-interface textfield

这是我的代码。我想让用户根据需要添加一个新的文本字段,但是它只能添加一个文本字段。将为Participant循环工作吗?

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import java.awt.Color;
import java.awt.SystemColor;


    public class General {


        private JFrame frame;
        private JTextField textFirst;

        /**
         * Launch the application.
         */
    public static void main(String[] args) {

            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        General window = new General();
                        
                      window.frame.setVisible(true);
                    
                       } catch (Exception e) {
                        e.printStackTrace();
                    

                     }
                }
            });
        }

        /**
         * Create the application.
         */
        public General() {
            initialize();


        }

        /**
         * Initialize the contents of the frame.
         */
        private void initialize() {
            frame = new JFrame();
            frame.setBounds(100, 100, 450, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().setLayout(null);
            
            JLabel lblInsertParticipantsTerm = new JLabel("Insert Participants Term :");
            lblInsertParticipantsTerm.setFont(new Font("Tahoma", Font.BOLD, 12));
            lblInsertParticipantsTerm.setBounds(34, 32, 169, 14);
            frame.getContentPane().add(lblInsertParticipantsTerm);
            
            textFirst = new JTextField();
            textFirst.setBounds(23, 52, 180, 20);
            frame.getContentPane().add(textFirst);
            textFirst.setColumns(10);
            
            JButton button = new JButton("ADD");
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    JTextField newTextField = new JTextField(20);
                    frame.getContentPane().add(newTextField);
                    frame.validate();
                    frame.repaint();
                
                  }
            });
            button.setBounds(205, 51, 53, 23);
            frame.getContentPane().add(button);
            
            JTextArea textArea = new JTextArea();
            textArea.setBackground(SystemColor.control);
            textArea.setBounds(23, 52, 180, 199);
            frame.getContentPane().add(textArea);
        }
  }

1 个答案:

答案 0 :(得分:1)

您需要一个布局管理器。请执行以下操作:

frame.getContentPane().setLayout(new FlowLayout());