java - 检索在 JDialog 中输入的输入

标签 java user-interface modal-dialog jdialog

我扩展了 JDialog 以创建一个自定义对话框,用户必须在其中填写一些字段: dialog

我应该如何检索输入的数据?

我想出了一个可行的解决方案。它模仿 JOptionPane 但由于涉及静态字段,我做它的方式对我来说看起来很难看......这是我的代码:

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;
    }
}

正如我所说,这可以正常工作,但我想这可能会引发严重的并发问题......

有没有更简洁的方法来做到这一点?在 JOptionPane 中是如何完成的?

最佳答案

如果我这样做,我总是这样工作:

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:你的程序看起来很棒!

关于java - 检索在 JDialog 中输入的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2620448/

相关文章:

javascript - Android 网页 View 像素

java - Facebook 能否检测到我是否在 Java 应用程序中使用他们的私有(private) Graphql API?

java - Android:在加载内容时运行动画

javascript - Angular UI Modal 导致无限摘要循环

ruby-on-rails - ClientSideValidations 未显示在 Twitter Bootstrap-Modal Rails 3.2 中

winforms - 自动调整 WinForms 对话框大小以适合内部内容

java - 在 Java 中如何查找两个列表的相似程度?

java - 如何在 Java 中比较字符串?

user-interface - 重新设计复杂 UI 的技术

java - 在执行其他方法时在单独的线程上更新 GUI