use*_*445 2 java user-interface swing
我知道你可以通过输入创建一个按钮
JButton x= new JButton("Something");
x.addActionListener(this);
Run Code Online (Sandbox Code Playgroud)
但是我如何创建一个actionlistener,以便按钮为用户创建一个文本字段以提供输入....以及如何从该文本框中读取文本?
Swing没有像文本框那样的动物 - 你的意思是JTextField吗?如果是这样,...
new JTextField() add(...)适当的容器(如JPanel)将其添加到GUI中.getText()它来阅读文本,JTextField教程将解释所有这些.revalidate()和repaint()添加或删除组件后,在容器上,以使容器的布局管理器就会知道,以更新其布局和重绘自己.这只是需要做的事情的一般要点.如果您需要更具体的建议,请告诉我们您的问题的详细信息,您迄今为止尝试过的内容以及有效或失败的内容.
编辑
你问:
但是我该怎么做才能使textField成为"弹出"而不是当前容器的添加.我有它,以便它添加到当前容器......但这不是我需要的.
例如:
// myGui is the currently displayed GUI
String foo = JOptionPane.showInputDialog(myGui, "Message", "Title",
JOptionPane.PLAIN_MESSAGE);
System.out.println(foo);
Run Code Online (Sandbox Code Playgroud)
这看起来像这样:

例如:
JTextField fooField = new JTextField(15);
JTextField barField = new JTextField(15);
JPanel moreComplexPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
moreComplexPanel.add(new JLabel("Foo:"), gbc);
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.EAST;
moreComplexPanel.add(fooField, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.WEST;
moreComplexPanel.add(new JLabel("Bar:"), gbc);
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.EAST;
moreComplexPanel.add(barField, gbc);
int result = JOptionPane.showConfirmDialog(myGui, moreComplexPanel,
"Foobars Forever", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
System.out.println("foo = " + fooField.getText());;
System.out.println("bar = " + barField.getText());;
}
Run Code Online (Sandbox Code Playgroud)
看起来像这样:

| 归档时间: |
|
| 查看次数: |
3255 次 |
| 最近记录: |