简单的弹出式Java表单,至少包含两个字段

时间:2010-06-09 02:38:46

标签: java swing user-interface

当用户点击按钮时,我想显示一个至少应包含两个JTextField和两个JLabel的弹出窗体,因此不可能使用JOptionPane.showInputDialog

2 个答案:

答案 0 :(得分:40)

您至少应该考虑一种JOptionPane方法,例如showInputDialog()showMessageDialog()

附录:使用JOptionPane的选择更多地取决于模态的适用性,而不是所示组件的数量。另请参阅How to Make Dialogs

附录:如@camickr的评论中所述,您可以使用引用Dialog Focus 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();
            }
        });
    }
}

答案 1 :(得分:0)

使用小型UiBooster库,您可以用几行代码构建一个表单对话框。

FilledForm form = new UiBooster()
        .createForm("Personal informations")
        .addText("Whats your first name?")
        .addTextArea("Tell me something about you")
        .addSelection(
                "Whats your favorite movie?",
                Arrays.asList("Pulp Fiction", "Bambi", "The Godfather", "Hangover"))
        .show();

enter image description here