Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make JOptionPane.showConfirmDialog have No selected by default?

I implemented a Save As dialog in Java that prompts the user if the file already exists, and I want the No option to be selected by default. How do I do this?

Here is my current code:

JFileChooser chooser = new JFileChooser() {     public void approveSelection()     {         File selectedFile = getSelectedFile();         if (selectedFile != null && selectedFile.exists( ) )         {             int response = JOptionPane.showConfirmDialog(                     this,                     "The file " + selectedFile.getName() + " already exists."                         + " Do you want to replace the existing file?",                     getDialogTitle(),                     JOptionPane.YES_NO_OPTION,                     JOptionPane.WARNING_MESSAGE);             if (response != JOptionPane.YES_OPTION )             {                 return;             }         }          super.approveSelection();     } }; 
like image 389
splintor Avatar asked Sep 08 '09 18:09

splintor


People also ask

What is default data type in JOptionPane?

When I ask a user to enter a quantity for a program I have made using the code below, the default text is 3. String input = JOptionPane.

What does JOptionPane showConfirmDialog return?

It's simply returns the index starting from 0. See JavaDoc for more info.

How do I add options to JOptionPane in Java?

You can use any of the JOptionPane's option constants, you just need to supply a options array of size 4: public static void main(String[] args) { String[] options = new String[] {"Yes", "No", "Maybe", "Cancel"}; int response = JOptionPane. showOptionDialog(null, "Message", "Title", JOptionPane.

How do you cancel JOptionPane?

If it's really safe to just kill all JOptionPanes you can do something like this: public static void main(String[] args) { new Thread() { public void run() { for (int i = 0; i < 3; i++) { try { Thread. sleep(2000); } catch (InterruptedException e) { } JOptionPane. getRootFrame(). dispose(); } } }.


1 Answers

That's the first thing that comes to my mind.

//Custom button text Object[] options = {"Yes",                     "No"}; JOptionPane.showOptionDialog(this, "The file " + selectedFile.getName() +                    " already exists. Do you want to replace the existing file?",                    getDialogTitle(),                    JOptionPane.YES_NO_OPTION,                    JOptionPane.WARNING_MESSAGE,                    null, options, options[1]); 

But probably there's a better approach.

like image 75
Carlos Tasada Avatar answered Oct 05 '22 22:10

Carlos Tasada