tags:

views:

97

answers:

1

This is, I suppose, a very simple question for any Java programmer.

My question is as simple as this:

When the user clicks a button, I want to show a popup form that should have at least two JTextFields and two JLabels, so using JOptionPane.showInputDialog is not a possibility.

Thanks.

+6  A: 

You should at least consider one of the JOptionPane methods such as showInputDialog() or showMessageDialog().

Addendum: The choice to use JOptionPane hinges more on the suitability of modality, rather than on the number of components shown. See also How to Make Dialogs.

Addendum: As noted in a comment by @camickr, you can set the focus to a particular component using the approach discussed in Dialog Focus.

import java.awt.GridLayout;
import javax.swing.*;

class JOptionPaneTest {

    public static void main(String[] args) {
        String[] items = {"One", "Two", "Three", "Four", "Five"};
        JComboBox combo = new JComboBox(items);
        JTextField field1 = new JTextField("1234.56");
        JTextField field2 = new JTextField("9876.54");
        JPanel panel = new JPanel(new GridLayout(0, 1));
        panel.add(combo);
        panel.add(new JLabel("Field 1:"));
        panel.add(field1);
        panel.add(new JLabel("Field 2:"));
        panel.add(field2);
        int result = JOptionPane.showConfirmDialog(null, panel, "Test",
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (result == JOptionPane.OK_OPTION) {
            System.out.println(combo.getSelectedItem()
                + " " + field1.getText()
                + " " + field2.getText());
        } else {
            System.out.println("Cancelled");
        }
    }
}
trashgod
Sorry about the initial confusion between answer and example.
trashgod
How can I retrieve the input?
nunos
I've elaborated above and added a link to the tutorial.
trashgod
+1, for showing how an option pane can be used for this and for including a link to the tutorial. There is one problem with using a panel this way. Focus will appear on the button, not the text field which may be a problem. For a solution to this check out the "Dialog Focus" link: http://tips4java.wordpress.com/2010/03/14/dialog-focus/
camickr
@camickr: Thank you for the link to that very helpful article, which I've cited above. Your considerable experience often anticipates the next likely question. I welcome additions and corrections; please don't hesitate to edit my answers as the opportunity arises.
trashgod
I keep forgetting I can edit postings and it is easier to edit the posting to add a link. I'll try an remember the next time :)
camickr
+ You will soon earn the swing specialist badge ;-)
stacker