检索在JDialog中输入的输入 [英] Retrieve input entered in a JDialog
问题描述
我扩展了JDialog来创建一个自定义对话框,用户必须在其中填充一些字段:
I extended JDialog to create a custom dialog where the user must fill some fields :
我应该如何检索输入的数据?
How should I retrieve the data entered ?
我想出了一个行之有效的解决方案.它模仿了JOptionPane,但是由于涉及到静态字段,所以我的操作方式对我来说很难看……这大致是我的代码:
I came up with a solution that works. It mimics JOptionPane but the way I do it looks ugly to me because of the static fields involved... Here is roughly my code :
public class FObjectDialog extends JDialog implements ActionListener {
private static String name;
private static String text;
private JTextField fName;
private JTextArea fText;
private JButton bAdd;
private JButton bCancel;
private FObjectDialog(Frame parentFrame) {
super(parentFrame,"Add an object",true);
// build the whole dialog
buildNewObjectDialog();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==bAdd){
name=fName.getText();
text=fText.getText();
}
else {
name=null;
text=null;
}
setVisible(false);
dispose();
}
public static String[] showCreateDialog(Frame parentFrame){
new FObjectDialog(parentFrame);
String[] res={name,text};
if((name==null)||(text==null))
res=null;
return res;
}
}
就像我说的那样,它可以正常工作,但是我想这可能会引发严重的并发问题...
As I said, that works properly, but I guess that might raise serious concurrency issues...
是否有一种更清洁的方式来做到这一点?在JOptionPane中如何完成?
Is there a cleaner way to do that ? How is it done in JOptionPane ?
推荐答案
如果我这样做,我总是会这样工作:
If I do this, I always works like this:
FObjectDialog fod = new FObjectDialog(this);
fod.setLocationRelativeTo(this); // A model doesn't set its location automatically relative to its parent
fod.setVisible(true);
// Now this code doesn't continue until the dialog is closed again.
// So the next code will be executed when it is closed and the data is filled in.
String name = fod.getName();
String text = fod.getText();
// getName() and getText() are just two simple getters (you still have to make) for the two fields their content
// So return textField.getText();
希望这会有所帮助!
PS:您的程序看起来很棒!
Hope this helps!
PS: Your program looks great!
这篇关于检索在JDialog中输入的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!