How To Make Message Boxes In Java

Message boxes are used to display alerts and information messages to the user. It’s very easy to make Message Boxes in .NET languages, however in Java programming language it’s not very easy like in vb/c#. In Java we can use JOptionPane to display messages.

The JOptionPane provides various types of message boxes as follows :
  1. A simple message box that has one button.
  • This type of message box is used only for showing appropriate message and user will end the message box by clicking the ‘Ok’ button.
    3.  An input box that contains two buttons ‘Ok’ and ‘Cancel’.

    2.  A message box that has two or three buttons. You can set several values for viewing many message box as follows :
  • ‘Yes’ and ‘No’
  • ‘Yes, ‘No’ and ‘Cancel’
  • ‘Ok’, and ‘Cancel’
The JOptionPane has three methods as follows :
  • showMessageDialog() – It is used to display a simple message.
  • showConfirmDialog() – It is used to asks the user for confirmation by displaying message.
  • showInputDialog() – It is used to prompt for inputting.
Now we’ll see how to make those 3 types of JOptionPane Message Boxes

NOTE 1 : You must use import javax.swing.JOptionPane; namespace in order to make the program work.

NOTE 2 : All you have to do is change INFORMATION_MESSAGE with WARNING_MESSAGE and ERROR MESSAGE.


Simple Message Box(showMessageDialog()) :
1. Information Message
 Codes :
    JOptionPane.showMessageDialog(null,
        "Hey, It's me Mohamed Shimran",
        "Ultimate Programming Tutorials",
        JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);

Image :
information message box

2. Warning Message
    Codes :
 JOptionPane.showMessageDialog(null,
        "Hey, It's me Mohamed Shimran",
        "Ultimate Programming Tutorials",
        JOptionPane.WARNING_MESSAGE);
    System.exit(0);

Image :

3. Error Message
   Codes :
 JOptionPane.showMessageDialog(null,
        "Hey, It's me Mohamed Shimran",
        "Ultimate Programming Tutorials",
        JOptionPane.ERROR_MESSAGE);
    System.exit(0);

Image :
ERROR_MESSAGEBOX

Confirm Message Box(showConfirmDialog()) :
Codes :

  int message = JOptionPane.showConfirmDialog(null,
        "Hey, It's me Mohamed Shimran",
        "Ultimate Programming Tutorials",
        JOptionPane.ERROR_MESSAGE);
  if (message == JOptionPane.YES_OPTION)
    {
 //if yes clicked
      System.exit(0);
    }
 else
 {
   System.exit(0);
 //if no clicked
 }

Image :
confirm_dialog

Input Message Box(showInputDialog())
Codes :
//Prompt the user
    String name = JOptionPane.showInputDialog(null, 
 "Hello?", 
 "Ultimate Programming Tutorials",
 JOptionPane.WARNING_MESSAGE);
    System.exit(0);

Image :
show input dialog

That's all :D

1 comments:

Post a Comment