繁体   English   中英

当我单击“添加”按钮时,我想添加文本字段。 但它不起作用。 帮我

[英]I want to add text field when i clicked the button “add”. But it doesn't work. Help me

这是我的代码。 我想让用户根据需要添加一个新的文本字段,但它只能添加一个文本字段。 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); } }

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM