Reading data from keyboard Java (First form) This way of reading data from Java is perhaps the simplest and easy to understand when we are beginning to write programs in Java.
To do so, we will stand with the JOptionPane class, which will show a dialog box where you can enter data for any process that we require of our program. This class is part of the javax.swing package, container has also to other elements or classes for building graphical user interfaces.
The class contains methods we can easily use which are:
showConfirmDialog - Used to present a confirmation dialog box
showMessageDialog - Used to display a simple message on the screen as a warning or a error.
showInputDialog - That we used to enter data to our application for processing.
For now, we will focus our attention on showInputDialog method that will help us achieve our mission to read data from the keyboard. This method has several ways of which we we assert, the most common:
static String showInputDialog (Object message)
dialog box displays a data entry in the center of the screen
static String showInputDialog (Component component, Object message)
dialog box displays a data entry refers to the center of the specified component.
static String showInputDialog (Component component, Object message, Object valorInicial)
dialog box displays a data entry refers to the center of the specified component with an initial value for the input.
static String showInputDialog (Component component, Object message, String title, int type)
dialog box displays a data entry refers to the center of the specified component with an initial value for the entry and icon specified by a kind of dialogue with the user.
methods for the parameters are:
component. is the component which refers to the dialog box focus when the component is not specified, the screen is taken as the reference and the dialog box appears in the center of it.
message. is the message or information presented to the user want to let you know the data that we require that you enter.
valorInicial. is the value that is set by default for data entry. Appears within the text of the dialog box.
title. is the message that appears in the title bar of our dialog.
type. is the kind of message that will be presented to the user represented by an icon. Icons for the dialog box can be:
ERROR_MESSAGE - An error message
INFORMATION_MESSAGE - An informational message
WARNING_MESSAGE - A warning message
QUESTION_MESSAGE - A query message
PLAIN_MESSAGE - A message without icon, message
plane
showInputDialog The method returns the text field value or null pressing the cancel button.
Example:
1. Import javax.swing.JOptionPane;
2.
3. public class Entry {
4. public static void main (String args []) {
5. String name = JOptionPane. ShowInputDialog (null, "Enter your name:", "Your name here", JOptionPane.INFORMATION_MESSAGE)
6. System. exit (0);
7.}
8.
}