29

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();
    }
};
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
splintor
  • 9,924
  • 6
  • 74
  • 89

5 Answers5

25

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.

NightFalcon
  • 102
  • 1
  • 9
Carlos Tasada
  • 4,438
  • 1
  • 23
  • 26
18

Use this constructor:

JOptionPane(Object message, int messageType, int optionType,
            Icon icon, Object[] options, Object initialValue)

where options specifies the buttons, and have initialValue (one of the options values) specify what the default is.

Update: You can call showOptionDialog rather than showConfirmDialog. The former takes options and initialValue parameters.

Vinay Sajip
  • 95,872
  • 14
  • 179
  • 191
  • 2
    But I don't want to specify the "Yes" and "No" myself - I want the system to take its defaults. Can this be done? – splintor Sep 08 '09 at 19:45
  • Also, after I create a new object using this ocnstructor, how do I show the modal confirm dialog? – splintor Sep 08 '09 at 19:45
  • after using the constructor, you call optionPane.createDialog(parent, "Title").setVisible(true) – Koen Weyn Sep 09 '09 at 12:44
  • 1
    The only other option for the initial question that I see is to override the installed OptionPaneUI. Have a look at BasicOptionPaneUI.getInitialValueIndex(). But IMO the solutions suggested above, are much more simpler. – Koen Weyn Sep 09 '09 at 12:53
  • @Koen Weyn : Thanks. I guess I'll use the showOptionsDialog option, as the createDialog seems cumbersome. How do I get the user selection when using createDialog? In any case, I find it very strange that Swing don't have a built-in support for this. – splintor Sep 10 '09 at 06:02
  • 1
    Unfortunately, this prevents Y and N on the keyboard operating the buttons. – Boann Nov 30 '11 at 23:47
  • I was frustrated by the fact that this way didn't work for the Y and N keys. And then I checked the simplest way (as in the original question, with Yes as the default) and noticed that on my Sun JRE 1.6 running on Windows 7, it didn't work for the Y and N keys either. – MB. Apr 21 '12 at 13:54
10

This is my solution:

import java.awt.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;


public class NegativeDefaultButtonJOptionPane {

public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType) {
    List<Object> options = new ArrayList<Object>();
    Object defaultOption;
    switch(optionType){
    case JOptionPane.OK_CANCEL_OPTION:
        options.add(UIManager.getString("OptionPane.okButtonText"));
        options.add(UIManager.getString("OptionPane.cancelButtonText"));
        defaultOption = UIManager.getString("OptionPane.cancelButtonText");
        break;
    case JOptionPane.YES_NO_OPTION:
        options.add(UIManager.getString("OptionPane.yesButtonText"));
        options.add(UIManager.getString("OptionPane.noButtonText"));
        defaultOption = UIManager.getString("OptionPane.noButtonText");
        break;
    case JOptionPane.YES_NO_CANCEL_OPTION:
        options.add(UIManager.getString("OptionPane.yesButtonText"));
        options.add(UIManager.getString("OptionPane.noButtonText"));
        options.add(UIManager.getString("OptionPane.cancelButtonText"));
        defaultOption = UIManager.getString("OptionPane.cancelButtonText");
        break;
        default:
            throw new IllegalArgumentException("Unknown optionType "+optionType);
    }
    return JOptionPane.showOptionDialog(parentComponent, message, title, optionType, JOptionPane.QUESTION_MESSAGE, null, options.toArray(), defaultOption);
}

}
subes
  • 1,832
  • 5
  • 22
  • 28
8

If you don't want to hardcode "Yes" and "No" (for instance when your app is localized for other languages), you can use UIManager resources:

UIManager.getString("OptionPane.yesButtonText", l)
UIManager.getString("OptionPane.noButtonText", l)
Koen Weyn
  • 989
  • 1
  • 7
  • 12
  • There is still the issue of the order of the buttons. On gtk, the user can actually specify the order using gtk-alternative-button-order=1. I don't know how you can find the order for the current platform and setting. – Roel Spilker Feb 10 '10 at 13:40
  • And I hope that using the showConfirmDialog handles this depending on the platform look and feel :-) – Roel Spilker Feb 10 '10 at 13:42
  • @RoelSpilker OptionPane.buttonOrientation, OptionPane.isYesLast, etc. Or highjack BasicOptionPaneUI's whole button panel. – Hakanai May 26 '14 at 13:41
1

For the above example, it is JOptionPane.showOptionDialog Those arguments can no be passed to showConfirmDialog because it does not have them.

More people might be looking for this so why not offer a "working" solution.

Cristian
  • 11
  • 1