Tuesday, November 29

GUI Input and output with JOptionPane - Java Tutorial

Analogous to Standard input and output, This is another easy way to provide GUI input and output based on message dialog or ( prompt ) by using JOptionPane class as the same with the following example to show message dialog.

JOptionPane.showMessageDialog(null, "Welcome to Java");

There are two arguments 1- JOptionPane.showMessageDialog for the class and 2- welcome to Java which appears in the dialog message, null means to put the message dialog in the center of the screen.

For input data it is the same, but we change Message with "Input"  as this one.

JOptionPane.showInputDialog(null, "Type question here or anything");

Absolutely simple and amazing with this to get and enter data to the program. I will show you an example completed code to illustrate our topic about message dialog, but first you may want to know there are two types of windows - a general purpose frame and a special purpose dialog that we are discussing and they are in javax.swing package.

A general purpose frame that we can create it with JFrame as this simple code with explanation.

import javax.swing.*;   // import statement ( package )
public class You_Java  
   public static void main(String[] args)
   JFrame windowFrame;   // General JFrame has the name windowFrame
   windowFrame = new JFrame();
   windowFrame.setSize(400,300);   // Frame size
   windowFrame.setVisible(true);   // Visibility true

   JOptionPane.showMessageDialog(null, "Welcome to Java");   // Show message and we used null
   JOptionPane.showMessageDialog(windowFrame, "Welcome to Java"); // We used here our window name

In the above code we use JOptionPane  dialog message with different placement on the screen and when I added null I told the message there is no Frame, in case of windowFrame I told the dialog box to the position of the appearance. 

Let's get back to the special purpose dialog with adding simple code that asks to enter any name + Welcome to Java.
import javax.swing.*;   // Import statement for the package
public class You_Java 
    public static void main(String[] args)
        String name;   // Variable of string type
        name = JOptionPane.showInputDialog(null, "What is your name" + "?");  // Input Dialog
        JOptionPane.showMessageDialog(null, "Welcome to Java " + name);  // Message welcome with name


That is!. easy and nice and if we want to ask multiple questions we just add Variables to the data type of string, for instance:

String name, age, qualifications;

Or as this one.

String name;
String age;
String qualifications;

There is no difference between them, but before you get Input and output you should know the data type of 
( String ) is not responsible for all purposes and carry out them such as subtraction numbers or multiplication