Java:showInputDialog中的自定义按钮

问题描述 投票:16回答:2

如何将自定义文本添加到JOptionPane.showInputDialog的按钮?

我知道这个问题JOptionPane showInputDialog with custom buttons,但是它没有回答所提出的问题,它只是将它们引用到JavaDocs,而JavaDocs却没有回答。

到目前为止的代码:

Object[] options1 = {"Try This Number",
                 "Choose A Random Number",
                 "Quit"};

JOptionPane.showOptionDialog(null,
                 "Enter a number between 0 and 10000",
                 "Enter a Number",
                 JOptionPane.YES_NO_CANCEL_OPTION,
                 JOptionPane.PLAIN_MESSAGE,
                 null,
                 options1,
                 null);

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9pazVIMC5wbmcifQ==” alt =“我希望它看起来如何”>

我想为此添加一个文本字段。

java swing joptionpane
2个回答
25
投票

您可以使用自定义组件而不是字符串消息,例如:

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class TestDialog {

    public static void main(String[] args) {
        Object[] options1 = { "Try This Number", "Choose A Random Number",
                "Quit" };

        JPanel panel = new JPanel();
        panel.add(new JLabel("Enter number between 0 and 1000"));
        JTextField textField = new JTextField(10);
        panel.add(textField);

        int result = JOptionPane.showOptionDialog(null, panel, "Enter a Number",
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
                null, options1, null);
        if (result == JOptionPane.YES_OPTION){
            JOptionPane.showMessageDialog(null, textField.getText());
        }
    }
}

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9aSGpXdy5wbmcifQ==” alt =“在此处输入图像描述”>


9
投票

看看How to Make Dialogs: Customizing Button Text

以下是示例:

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS8yWHBxNS5wbmcifQ==” alt =“在此处输入图像描述”>

Object[] options = {"Yes, please",
                    "No, thanks",
                    "No eggs, no ham!"};
int n = JOptionPane.showOptionDialog(frame,//parent container of JOptionPane
    "Would you like some green eggs to go "
    + "with that ham?",
    "A Silly Question",
    JOptionPane.YES_NO_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null,//do not use a custom Icon
    options,//the titles of buttons
    options[2]);//default button title
© www.soinside.com 2019 - 2024. All rights reserved.