Tino Intro To Java

Last modified: January 09, 2024

GUI Input and Output

Rather than use a Scanner object requiring users to type everything into a command-line console, many programs use GUI elements to handle user input. GUI stands for Graphical User Interface. In CodeHS, the function like readLine made a dialog box pop up and the user typed answers into the dialog box. In this page, you will learn how to do something similar to that.

Here is an example of GUI input and output in Java:

// Import the GUI dialog class
import javax.swing.JOptionPane;

public class GUITest {

    public static void main(String[] args) {

        // Declare two variables, a String and integer
        String name;
        int age;

        // GUI Input Box returns user input as a String
        name = JOptionPane.showInputDialog("Enter your name");

        // Since GUI Input Boxes return Strings only, we must save the
        // result to a String and then convert it to an integer
        String answer = JOptionPane.showInputDialog("Enter your age");

        // The Integer class has a method to convert a String into an int
        age = Integer.parseInt(answer);

        // GUI Output Box
        String message = "Hello there, " + name 
        + "! In ten years you will be " + (age + 10);
        JOptionPane.showMessageDialog(null, message);

        // Console output
        System.out.println("Hello there, " + name + "! In ten years you will be " +
                           (age + 10));
    }
}

Things to notice:

  1. In order to use GUI dialog boxes, you must import javax.swing.JOptionPane;
  2. Since GUI input boxes return user input as a String, you are responsible for converting the string to the desired type.
  3. There are methods in the Integer and Double classes that can parse a String and return an int or double as shown below.
Integer.parseInt("123"); // converts "123" into integer 123
Double.parseDouble("1.5"); // converts "1.5" into double 1.5

Dark Mode

Outline