JOptionPane showOptionDialog Code Example
showMessageDialog and showInputDialog, JOption showOptionDialog is pretty easy and straight forward.
Unlike other JOptionPanes, i.e., Simple JOption showOptionDialog
Execute below code.
[
import javax.swing.JOptionPane; public class ShowOptionDialog { public static void main(String args[]) { handleQuit(); } public static void handleQuit() { int choice=JOptionPane.showOptionDialog(null, "Do you want to close system",
"Close System",JOptionPane.YES_NO_OPTION,null, null, null); if(choice==JOptionPane.YES_NO_OPTION) { System.exit(0); } } }
]
Code Analysis
Above code does a simple task.Method handQuit() has an Option JOptionPane that pops up requesting user if to exit the program.If the user clicks YES option, the program is exited using System.exit(0) method
Adding ImageIcon to JOptionPane.showOptionDialog
[
import javax.swing.JOptionPane; import javax.swing.ImageIcon; /** * * @author acer */public class ShowOptionDialog { public static void main(String args[]) { handleQuit(); } public static void handleQuit() { int choice=JOptionPane.showOptionDialog(null, "Do you want to close system","Close System", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,new ImageIcon(ShowOptionDialog.class.getResource("server.jpg")), null, null); if(choice==JOptionPane.YES_NO_OPTION) { System.exit(0); } } }
]
Output
new ImageIcon(ShowOptionDialog.class.getResource("server.jpg")) code adds icon to the Option dialog
How to control JOptionPane showOptionDialog Prompts
Below code shows how you can control dialog options.
[
import javax.swing.JOptionPane; import javax.swing.ImageIcon; /** * * @author acer */public class ShowOptionDialog { public static void main(String args[]) { handleQuit(); } public static void handleQuit() { Object [] options={"Okay","Cancel"}; int choice=JOptionPane.showOptionDialog(null, "Do you want to close system","Close System", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,
new ImageIcon(ShowOptionDialog.class.getResource("server.jpg")), options, options[0]); if(choice==JOptionPane.YES_OPTION) { System.exit(0); } } }
]
Above code remains the same.We have just introduced options.By setting options[0] ,Okay option is selected by default.Striking enter button will return Okay