Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple popup java form with at least two fields

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.

like image 561
nunos Avatar asked Jun 09 '10 02:06

nunos


People also ask

What is JDialog in Java?

JDialog is a part Java swing package. The main purpose of the dialog is to add components to it. JDialog can be customized according to user need . Constructor of the class are: JDialog() : creates an empty dialog without any title or any specified owner.

How do you create a dialogue box in Java?

Message dialogs are created with the JOptionPane. showMessageDialog() method. We call the static showMessageDialog() method of the JOptionPane class to create a message dialog.


1 Answers

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, cited here.

image

package gui;

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

/** @see https://stackoverflow.com/a/3002830/230513 */
class JOptionPaneTest {

    private static void display() {
        String[] items = {"One", "Two", "Three", "Four", "Five"};
        JComboBox<String> 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");
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                display();
            }
        });
    }
}
like image 75
trashgod Avatar answered Nov 15 '22 16:11

trashgod