Retrieve input entered in a JDialog

Jules Olléon picture Jules Olléon · Apr 12, 2010 · Viewed 7.4k times · Source

I extended JDialog to create a custom dialog where the user must fill some fields : dialog

How should I retrieve the data entered ?

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...

Is there a cleaner way to do that ? How is it done in JOptionPane ?

Answer

Martijn Courteaux picture Martijn Courteaux · Apr 12, 2010

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();

Hope this helps!
PS: Your program looks great!