Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

java - 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();
    }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...