【问题标题】:Retrieve input entered in a JDialog检索在 JDialog 中输入的输入
【发布时间】:2010-04-12 07:19:15
【问题描述】:

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

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

我想出了一个可行的解决方案。它模仿了 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 中是如何实现的?

【问题讨论】:

标签: java user-interface modal-dialog jdialog


【解决方案1】:

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

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

【讨论】:

  • 噢噢噢噢!我不知道为什么我被那些静态字段卡住了......在我看来,对象在处理完窗口后就被破坏了,但事实并非如此。谢谢!
【解决方案2】:

如果您打算同时显示多个对话框,那么您会遇到并发问题,否则不会。然而,摆脱所有静态的东西会使设计更干净、更安全、更容易测试。只需通过调用代码控制对话框的创建和显示,您不需要任何静态的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 2016-03-18
    相关资源
    最近更新 更多