Java: Custom Buttons in showInputDialog

*爱你&永不变心* 提交于 2019-12-21 03:42:08

问题


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 answer the question asked, it just references them to JavaDocs, which doesn't answer it.

Code So Far:

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

I would like to add a text field to this.


回答1:


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




回答2:


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

Here is an example given:

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


来源:https://stackoverflow.com/questions/13334198/java-custom-buttons-in-showinputdialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!