Question

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 ?

Was it helpful?

Solution

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!

OTHER TIPS

If you intend to display multiple dialogs at the same time, then you have concurrency issues, not otherwise. However, getting rid of all the static stuff would make the design cleaner, safer and easier to test. Just control the creation and showing of the dialog from the calling code and you don't need any static stuff.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top