What are the different types of JOptionPane dialogs in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

The JOptionPane is a subclass of JComponent class which includes static methods for creating and customizing modal dialog boxes using a simple code. The JOptionPane is used instead of JDialog to minimize the complexity of the code. The JOptionPane displays the dialog boxes with one of the four standard icons (question, information, warning, and error) or the custom icons specified by the user.

JOptionPane class is used to display four types of dialog boxes

  • MessageDialog -  dialog box that displays a message making it possible to add icons to alert the user.
  • ConfirmDialog  -  dialog box that besides sending a message, enables the user to answer a question.
  • InputDialog       -  dialog box that besides sending a message, allows entry of a text.
  • OptionDialog    -  dialog box that covers the three previous types.

Example

import javax.swing.*;
public class JoptionPaneTest {
   public static void main(String[] args) {
      JFrame frame = new JFrame("JoptionPane Test");
      frame.setSize(200, 200);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
      JOptionPane.showMessageDialog(frame, "Hello Java");
      JOptionPane.showMessageDialog(frame, "You have less amount, please recharge","Apocalyptic message", JOptionPane.WARNING_MESSAGE);
      int result = JOptionPane.showConfirmDialog(null, "Do you want to remove item now?");
      switch (result) {
         case JOptionPane.YES_OPTION:
         System.out.println("Yes");
         break;
         case JOptionPane.NO_OPTION:
         System.out.println("No");
         break;
         case JOptionPane.CANCEL_OPTION:
         System.out.println("Cancel");
         break;
         case JOptionPane.CLOSED_OPTION:
         System.out.println("Closed");
         break;
      }
      String name = JOptionPane.showInputDialog(null, "Please enter your name.");
      System.out.println(name);
      JTextField userField = new JTextField();
      JPasswordField passField = new JPasswordField();
      String message = "Please enter your user name and password.";
      result = JOptionPane.showOptionDialog(frame, new Object[] {message, userField, passField},
      "Login", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
      if (result == JOptionPane.OK_OPTION)
      System.out.println(userField.getText() + " " + new String(passField.getPassword()));
      System.exit(0);
   }
}

Output





raja
Published on 06-Jul-2019 06:54:15
Advertisements