Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Custom Buttons in showInputDialog

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

How I want it to look

I would like to add a text field to this.

like image 582
ZuluDeltaNiner Avatar asked Nov 11 '12 18:11

ZuluDeltaNiner


People also ask

How do you add a button in JOptionPane?

showOptionDialog( panel, "Choose one of the following options for Category " + category + ". \n" + "If skip is available, you may choose it to skip this category.", "Select option", optionType, JOptionPane. INFORMATION_MESSAGE, null, options, options[0]);

What does the showInputDialog method do?

Method showInputDialog returns a String containing the characters typed by the user. We store the String in variable name . If you press the dialog's Cancel button or press the Esc key, the method returns null and the program displays the word “null” as the name.


1 Answers

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

like image 176
tenorsax Avatar answered Oct 18 '22 05:10

tenorsax