Dialog Boxes for Input /Output

2.6 Dialog Boxes for Input /Output

Display Message in Dialog Box
import javax.swing.JOptionPane;    // Needed for Dialog Box

/**
 *   This program demonstrates
 *   showMessageDialog.
 */
public class MessageDialogDemo
{
   public static void main(String[] args)
   {
      JOptionPane.showMessageDialog(null, "Welcome");
   }
}

Output :

Reading String Input
import javax.swing.JOptionPane;    // Needed for Dialog Box

/**
 *   This program demonstrates
 *   showInputDialog.
 */
public class InputDialogDemo
{
   public static void main(String[] args)
   {
      String name;

      // Get the user's name.
      name = JOptionPane.showInputDialog("What is your name? ");

      // Display message
      JOptionPane.showMessageDialog(null, "Hello " + name);
   }
}

Program Output

Reading Number Input

import javax.swing.JOptionPane;    // Needed for Dialog Box

/**
 *   This program find area of rectangle
 *   using input output dialog box.
 */
public class RectangleTest
{
   public static void main(String[] args)
   {
      String input;     // To hold String input.
      int    length;    // To hold length.
      int    width;     // To hold width.
      int    area;      // To hold area.

      // Prompt user to input length.
      input = JOptionPane.showInputDialog("Enter Length");

      // Convert the String input to an int.
      length = Integer.parseInt(input);

      // Prompt user to input width.
      input = JOptionPane.showInputDialog("Enter Width");

      // Convert the String input to an int.
      width = Integer.parseInt(input);

      // Calculate area of rectangle.
      area = length * width;

      // Display area of rectangle.
      JOptionPane.showMessageDialog(null,
                                    "Area of rectangle is " + area);
   }
}
Output :

No comments:

Post a Comment

Pages