Getting user data through dialogs boxes


We saw in the last article that the dialog boxes are very used to display messages (mainly for errors and alerts), and show how to do this in Java.


However, it can also be used (and we show how to do this) to receive data from the user by an interface more friendly and graphical :)





How to use dialog box to receive data from the user

For us 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;

Receiving information from the user through dialogs

It is a kind of class 'Scanner', where the user will type something and this information will be assigned to a string.

When we show information, we use the method showMessageDialog.
We will now use the method showInputDialog.

Note that it makes no sense to simply pop up a dialog box that receives user data. It takes Dialog Box that displays some information, like 'What's your name?', 'Login', 'Password' etc..
In the case of the method showInputDialog, it will receive a string (entered by the user) and displays a message dialog box, this message will be entered in parentheses method showInputDialog and everything that is typed by the user is stored in the string 'name' because we will ask the user name.


Soon after, we will display the user's name. How to display?
Now, through a dialog box that displays a text, that we have learned in the last lesson.

Our application asks that the customer's name and displays a gentle message


import javax.swing.JOptionPane;

public class receiveingData {
    
    public static void main(String[] args){
        String name;
        
        name = JOptionPane.showInputDialog("Enter your name, dear user.");
        
        JOptionPane.showMessageDialog(null,nome +"???\nWow, what a ugly name!\nAt least you know how to program in Java!");
    }

}

:


A useful method of the String class is the format, which formats the string, ie, change, change the string to the way you want.
In our case, it would be useful to use this method as well:
name = String.format (name + "?? \ nWow, what a ugly name!\nAt least you know how to program in Java!");

And use the string 'name' String variable in JOptionPane.showMessageDialog thus:
JOptionPane.showMessageDialog (null, name);


In the next article we will show how to transform the information, which is of type String, in types integer, float, double etc.

No comments: