Displaying messages by dialog boxes


Dialog boxes are most simpler kind of graphics that we will se in our Java course. But no less important, and certainly the most common that we see.

Are seen as error messages and warnings in the operating systems.
We will show how to declare and display messages via dialog boxes.



How to use dialog boxes in Java

For we use dialog boxes we need to import a class package (package) javax.swing, which is a package that will use a lot in our Java GUI applications.

This class is static and is called JOptionPane.
Get used to these names beginning with J: JLabel, JButton, JTextField ...

The import is therefore:
import javax.swing.JOptionPane;

Viewing messages in dialogs

To view messages in a dialog box, will use the method showMessageDialog, which takes two arguments.
The first refers to the position of the dialog box (for now, not be concerned with it and send the argument 'null') and the second is the string that appears.

A complete example of its first graphics program in Java is:


import javax.swing.JOptionPane;

public class dialogBox {
    
    public static void main(String[] args){
        JOptionPane.showMessageDialog(null,"My first graphic program!\n Thanks, Progressive Java Course!");
    }

}


Note that we do not need to declare an object of class JOptionPane because the class is static.
Later on, when we explain better Object Orientation and classes, will know better what that means.

See that we can display a string so the way it was shown in the program, or declaring a variable of type String, 'message' and use this way:
JOptionPane.showMessageDialog (null, message);

For example, for the user to enter a string through an object 'input' class 'Scanner', use the command:
message = entrada.nextLine();

Then, an application that receives a string from the user and displays the dialog would be:

import javax.swing.JOptionPane;
import java.util.Scanner;
public class dialogBoxes {
    
    public static void main(String[] args){
        String text;
        Scanner input = new Scanner(System.in);
        
        System.out.print("Enter something to be displayed: ");
        text = input.nextLine();
        JOptionPane.showMessageDialog(null,mensagem);
    }

}



Note that by default, these examples shows a simple Java button 'OK' and options to minimize and close, and a Java icon and another exclamation.

All with very little code.
This is an advantage of the Java graphical programming. We can easily change these icons and put more buttons and features, as we will see throughout the course.


No comments: