My question is how to temporary disable the OK button on JOptionPane input dialog until a key is pressed?
Asked
Active
Viewed 3,967 times
0
-
We need more info. Are you using default dialogs (JOptionPane.showXXXXDialog) or are making you own dialog? – PhoneixS Nov 05 '12 at 09:03
-
Maybe you can see http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html#stayup. It explain how to validate user input by adding a listener and checking values before closing the dialog. In your case, validating may consist in check if the input is the key that you are searching for. – PhoneixS Nov 05 '12 at 09:06
-
JOptionDialog is a ready-to-use class with a limited set of configuration options. One solution would be to display the dialog again after the user presses OK. Bit otherwise you need to make your own dialog using the JDialog class. There is a nice tutorial here: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html – Jakub Zaverka Nov 05 '12 at 09:16
-
It isn't possible with JOptionPane, but it is possible with a `JDialog` http://docs.oracle.com/javase/6/docs/api/javax/swing/JDialog.html – Mob Nov 05 '12 at 09:01
-
This is not true. See my answer. – Eng.Fouad Nov 05 '12 at 09:26
-
@Eng.Fouad You are still core-coding the components of the pane. I think the OP meant with the default JOptionPane. – Mob Nov 05 '12 at 09:31
-
You can add a `JOptionPane` to a `JDialog`, as suggested [here](http://stackoverflow.com/a/12451673/230513) and [here](http://stackoverflow.com/a/13228911/230513). – trashgod Nov 05 '12 at 11:11
1 Answers
1
Here is an example:
JPanel pan = new JPanel(new BorderLayout());
final JTextField txt = new JTextField(10);
final JButton ok = new JButton("OK");
ok.setEnabled(false);
ok.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String input = txt.getText();
System.out.println("The input is: " + input);
/* close the dialog */
Window w = SwingUtilities.getWindowAncestor(ok);
if(w != null) w.setVisible(false);
}
});
txt.getDocument().addDocumentListener(new DocumentListener()
{
@Override
public void removeUpdate(DocumentEvent e)
{
if(e.getDocument().getLength() == 0) ok.setEnabled(false);
}
@Override
public void insertUpdate(DocumentEvent e)
{
if(e.getDocument().getLength() > 0) ok.setEnabled(true);
}
@Override
public void changedUpdate(DocumentEvent e){}
});
pan.add(txt, BorderLayout.NORTH);
JOptionPane.showOptionDialog(null, pan, "The Title", JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, new JButton[]{ok}, ok);

Eng.Fouad
- 115,165
- 71
- 313
- 417