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(); } };
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.
It's simply returns the index starting from 0. See JavaDoc for more info.
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.
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(); } } }.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With