问题描述
我在Java中创建了一个框架
,其中包含一些文本字段和按钮
。假设用户想要更多的文本字段(例如添加更多数据),我想放一个按钮
,当用户点击按钮
,然后会出现一个新的 textfield
。然后用户可以在其中填充数据,然后再单击按钮
将出现另一个 textfield
。
我该怎么办?我需要为按钮编写什么代码才能通过单击按钮显示越来越多的文本字段?
谢谢!
I have created a frame
in Java which has some textfields and buttons
in it. Assuming that user wants more textfields (for example to add more data), I want to put a button
and when a user clicks the button
, then a new textfield
should appear. then user can fill data in it and again by clicking that button
another textfield
should appear.How can I do this ? What code I need to write for the button to show more and more text fields by clicking button?Thank you !
推荐答案
明智的是,不要在 JFrame中添加组件
直接将它们添加到 JPanel
。虽然与你的问题有关,但请看一下这个小例子,希望能给你一些提示,否则问我什么是出界的。
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();
}
});
}
}
这篇关于Java-如何通过单击按钮添加更多文本字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!