使用选项和文本字段弹出Swing窗口

时间:2014-12-17 04:52:40

标签: java swing joptionpane jdialog

鉴于此类代码:

Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
                frame,
                "Complete the sentence:\n"
                + "\"Green eggs and...\"",
                "Customized Dialog",
                JOptionPane.PLAIN_MESSAGE,
                icon,
                possibilities,
                "ham");

enter image description here

你可以看到它弹出一个带有选项的窗口。但是,我能和JTextField平行吗?因此,我可以从optiontext field获得输入。

1 个答案:

答案 0 :(得分:3)

在一轮谈判中,是的......

Breakfast

JPanel fields = new JPanel(new GridLayout(2, 1));
JTextField field = new JTextField(10);
JComboBox<String> comboBox = new JComboBox<>(new String[]{"ham", "spam", "yam"});

fields.add(field);
fields.add(comboBox);

int result = JOptionPane.showConfirmDialog(null, fields, "Breakfast", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
switch (result) {
    case JOptionPane.OK_OPTION:
        // Process the results...
        break;
}

如果您将JComponent传递给JOptionPane作为message参数,人们会忘记或者没有意识到,它会被添加到JOptionPane,它真的相当灵活和强大