Java: Custom Buttons in showInputDialog

后端 未结 2 1991
醉梦人生
醉梦人生 2021-02-12 21:57

How do you add custom text to the buttons of a JOptionPane.showInputDialog?

I know about this question JOptionPane showInputDialog with custom buttons, but it doesn\'t a

相关标签:
2条回答
  • 2021-02-12 22:57

    You can use custom component instead of a string message, for example:

    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());
            }
        }
    }
    

    enter image description here

    0 讨论(0)
  • 2021-02-12 22:58

    Have a look at How to Make Dialogs: Customizing Button Text.

    Here is an example given:

    enter image description here

    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
    
    0 讨论(0)
提交回复
热议问题