我在Java中创建了一个frame
,里面有一些textfields and buttons
。假设用户想要更多文本字段(例如添加更多数据),我想添加button
,当用户点击the button
时,就会出现新的textfield
。然后,用户可以通过点击button
应该出现的另一个textfield
来填充其中的数据。
我怎样才能做到这一点 ?我需要为按钮编写什么代码才能通过单击按钮显示越来越多的文本字段?
谢谢!
答案 0 :(得分:3)
明智的做法是,不要直接向JFrame
添加组件,而是将其添加到JPanel
。虽然与你的问题有关,但看看这个小例子,希望能够给你一些提示,否则问我什么是出界的。
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();
}
});
}
}
答案 1 :(得分:2)
假设您有一个名为panel
的主容器和一个已添加到button
的按钮变量panel
,您可以这样做:
// 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();
}
});
添加新文本字段时,您可能需要提及一些与布局相关的特性,具体取决于您使用的布局管理器(例如,如果您使用GridBagLayout
,则需要指定约束)。 / p>