【发布时间】:2014-10-27 18:10:58
【问题描述】:
我正在尝试使用JDialog 作为String 的输入。但我得到的文字是在我点击按钮之前的。
这是我的对话:
public class AddMemberDialog extends JDialog {
private JTextField name;
public AddMemberDialog() {
super(new JFrame("Add Member"), "Add Member");
this.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
this.setMinimumSize(new Dimension(500, 500));
this.name = new JTextField();
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
close();
}
});
this.setLayout(new GridLayout(2, 1, 5, 5));
this.add(name);
this.add(add);
this.pack();
}
private void close(){ this.dispose(); }
public String getName(){ return this.name.getText(); }
}
这是我用来到达String的方法:
AddMemberDialog input = new AddMemberDialog();
input.setLocationRelativeTo(this);
input.setVisible(true);
String txt = input.getName();
【问题讨论】:
-
您需要为您的按钮制作一个 ActionListener,然后仅在按下按钮后获取代码。我的代码 HERE 也有类似的问题
-
或者更确切地说,制作另一个按钮来处理它,因为我看到这个按钮用于关闭
-
在你的构造函数中,添加“setModal(true);”
-
但我的意思是
String txt = input.getName();在对话框打开时获取值,我想在它关闭时获取它 -
正确,因为它是自动执行的,从字面上看,它打开的那一秒,它就会接受输入。我是说,在按下按钮或其他东西之前不要接受输入,否则,你将无法获取输入