Is there a way to only have the OK button in a JOptionPane showInputDialog (and no CANCEL button)?

一笑奈何 提交于 2019-11-29 04:38:20
Eng.Fouad

Just add a custom JPanel as a message to JOptionPane.showOptionDialog():

String[] options = {"OK"};
JPanel panel = new JPanel();
JLabel lbl = new JLabel("Enter Your name: ");
JTextField txt = new JTextField(10);
panel.add(lbl);
panel.add(txt);
int selectedOption = JOptionPane.showOptionDialog(null, panel, "The Title", JOptionPane.NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options , options[0]);

if(selectedOption == 0)
{
    String text = txt.getText();
    // ...
}

JOptionPane.showInputDialog() returns the string the user has entered if the user clicks "OK" and returns null otherwise. See this:

Returns: user's input, or null meaning the user canceled the input

You can't do this using showInputDialog()

However, you can use JOptionPane#showOptionDialog():

Object[] buttons = {"OK"};
int res = JOptionPane.showOptionDialog(yourFrame,
                   "YourMessage","YourTitle",
                   JOptionPane....,
                   JOptionPane..., null, buttons , buttons[0]);

As @HovercraftFullOfEels stated on the comments, you can add JTextField to the dialog and achieve this.

Try:

JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");

I found in here

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