Concepts / Static Methods and the Class Name in Java

Static Methods and the Class Name in Java

A GUI program opens a window on the screen and interacts with the user through it, and a simple one can be written in only a few lines.

  • Programming

Predicting a Window You Have Never Built

Most of the Java programs you have written so far probably print text to the command line. This article starts from a different kind of program: one that opens its own window on the screen and talks to the user through that window. A program like this is called a GUI program, where GUI stands for graphical user interface. A GUI program does not have to be complicated. The smallest useful example is a Hello World program that greets the user by displaying the greeting in a window instead of in the terminal.

What do you think happens?

Before reading on, commit to a guess: when this program runs and the message Hello World! is passed to it, what does the user see on the screen, and what must happen before the program can finish?

  • Text appears in the terminal and the program ends immediately

  • A window appears with the message and an OK button, and the program waits until OK is clicked

  • A window appears, but the program ends without waiting for the user

Reveal answer
Answer:

A window appears with the message Hello World! and an OK button. The program waits for the user to read the message and click OK, and only after that click does the window close and the program finish.

The source describes this behavior directly: the window contains the message and the OK button, the program waits for the user to click the button, and clicking OK closes the window and ends the program. Writing your guess first lets you point to the exact moment your expectation and the real behavior part ways, if they do.

Reading the Three Lines That Matter

The program is saved in a file named HelloWorldGUI1.java. Read it before you run it and look for three things: the import line at the top, the class declaration, and the single statement inside main. Everything else in this article is built around those three lines.

Code walkthrough
import javax.swing.JOptionPane;

public class HelloWorldGUI1 {
    public static void main(String[] args) {
        JOptionPane.showMessageDialog(null, "Hello World!");
    }
}
  1. 1
    Line 1 imports javax.swing.JOptionPane so the class can be written with its simple name.
  2. 2
    Line 3 declares the class, which is the container for the program.
  3. 3
    Line 4 starts main, the place where execution begins.
  4. 4
    Line 5 is the only statement that does real work: it calls the static method showMessageDialog on the class name JOptionPane, passing null and the message text.
  • The import line makes the short name JOptionPane available to the code
  • The class declaration names the program
  • The single statement inside main does all of the visible work
  • The first argument, null, is a fixed part of this call
  • The second argument is the string that becomes the message the user reads
Output
A dialog window appears on screen containing the message Hello World! and an OK button. The program waits until the user clicks OK, then the window closes and the program ends.

Tracing the Call from Statement to Screen

The source explains the work behind the window in three parts. The program creates a window. It draws the contents of that window, including the message and the button. And it handles the event that is generated when the user clicks the button. A learner who has not built a GUI before might expect all three of these to require many lines of code. In this program they do not, because a single method call takes responsibility for all of them.

Programmain methodJOptionPanestatic methodDialog windowmessage and OK buttonUserreads and clicks OKcall showMessageDialogcreate windowdraw message and buttonshow Hello World!click OKprogram finishes
After the line JOptionPane.showMessageDialog(...) runs, which part hands work to which, and in what order, until the window and button appear and the program waits?

Read the diagram from top to bottom. Your program does one thing: it makes the call. From that point on, the work passes to JOptionPane, which creates the window and draws the message and button into it. The window then waits on the user. When the user clicks OK, the handling of that click is also done by the method, and the program finishes. Your code does not contain a loop waiting for the click or a line that closes the window. Those responsibilities belong to the method call.

JOptionPane and showMessageDialog as Roles

Definition

JOptionPane is a built-in class in the javax.swing package. Its purpose is to create simple dialog boxes. A dialog box is a small window that presents information and waits for a response from the user.

Definition

showMessageDialog() is a static method in the JOptionPane class. Nearly all of the work in the GUI program is done by this method: it handles creating the window, drawing its contents, and handling the OK click.

Because the method is static, you call it on the class name itself, JOptionPane, without first creating a JOptionPane object. The call takes two arguments in this program. The first is null. The source does not explain that argument in this section, so treat it for now as a fixed part of the call that this program always supplies. The second argument is the string that becomes the message the user reads.

Anatomy of the showMessageDialog Statement

Take the single statement apart and identify each piece. The leftmost name, JOptionPane, names the class. The name after the dot, showMessageDialog, names the static method that the class provides. The arguments in parentheses supply the information the method needs: null in the first position, and the message text in the second.

JOptionPaneclass nameshowMessageDialogstatic methodnullfirst argument, fixed inthis programHello World!second argument, themessage textprovides static methodargument 1argument 2
In this one line, which piece names the class, which names the method, and which supplies the message, and how do they relate to each other?

The relationship between the pieces is what matters. The class name tells Java where the method lives, the method name tells Java which action to perform, and the arguments tell that action what to display. Changing only the second argument changes the text in the window, while the structure of the statement stays the same.

Window, Message, and Button Nesting

When the program runs, the screen shows one window that contains two things the user interacts with: the message text and the OK button. The message is the content the second argument supplies. The button is the element whose click ends the program. Think of the window as the outer container, with the message and the button placed inside it.

Dialog windowthe whole dialogMessage textHello World!OK buttoncloses the window whenclickedcontainscontains
What is contained inside what on the screen: which element is the window, which holds the message text, and which holds the OK button?

Static Calls Compared With Object Method Calls

Many Java methods are called on an object, which you create first with new and then use through a variable. A static method works differently: it belongs to the class itself, so you call it through the class name. The table below contrasts the two styles. The object example is a generated illustration of the general pattern, not part of the source program.

AspectStatic method callMethod call on an object
How it is writtenClassName.methodName(...)variable.methodName(...)
Object needed firstNoYes, one created with new or obtained elsewhere
Example in this articleJOptionPane.showMessageDialog(null, "Hello World!")A generated pattern such as an object variable followed by a dot and a method name
Where the method is called fromThe class name, directlyThe object that the variable refers to

Calling a static method through the class name needs no object, which is why the GUI program can show a dialog in a single statement.

This is why no object is needed in the GUI program. The static method showMessageDialog can be invoked on JOptionPane directly, so the statement is complete with only the class name, the method name, and the arguments.

How the Import Line Shortens the Name

The first line of the program is import javax.swing.JOptionPane; Without an import, a class is referred to by its fully qualified name, which includes the package it lives in. The full name of this class is javax.swing.JOptionPane. Writing the full name every time you need the class would make the call harder to read. The import line tells the compiler that JOptionPane refers to javax.swing.JOptionPane, so the call can use the simple name JOptionPane.

java
Output
The same dialog appears as with the imported short name.
Notes on the code
  • This is the fully qualified form of the same call
  • Only the way the class name is written has changed
  • The class and the method are the same in both versions

Finding Where a GUI Run Goes Wrong

Suppose you run the program and something is wrong. The window does not appear, or it appears with the wrong text, or clicking OK does not end the program. The skill here is finding the stage where the result first differs from what the source describes. Work through the stages in order, and the first stage that fails is the one to investigate.

  1. 1
    Check that the program compiles and runs with the java command
  2. 2
    Check that a window appears on the screen
  3. 3
    Check that the window contains the message you passed in as the second argument
  4. 4
    Check that the window contains an OK button
  5. 5
    Check that clicking that button closes the window and ends the program

Each checkpoint tells you something specific. If the window appears with the right message, the call reached the screen. If the window appears but the button does nothing, the problem lies in the window's event handling, which in this program is supplied by JOptionPane. If the window shows the wrong text, look first at the second argument of the call. Reading the checkpoints in order keeps you from guessing.

Mistakes Beginners Make With Dialog Calls

  • Common mistake

    Treating the import line as the thing that makes the dialog appear

    Why it fails

    The import only lets the program use the simple name JOptionPane. The window comes from the call to showMessageDialog.

    Do this instead

    Look at the statement inside main to see what produces the window and message.

  • Common mistake

    Creating a JOptionPane object before calling the method

    What it looks like
    JOptionPane.showMessageDialog(null, "Hello World!");
    Why it fails

    showMessageDialog is a static method, so it is called on the class name without first creating an object.

    Do this instead

    Call the method directly on the class name JOptionPane.

  • Common mistake

    Assuming the first argument supplies the message text

    Why it fails

    In this program the first argument is null and the second is the string that becomes the message.

    Do this instead

    Read the arguments by position: the second one controls the displayed text.

  • Common mistake

    Writing code to handle the OK click for this simple dialog

    Why it fails

    The source states that the method handles the OK click, so the program needs no extra code for the click in this example.

    Do this instead

    When the button does nothing, check the call and the stages of the run rather than adding unrelated code.

Practice: Changing the Message Text

EASY

Without changing the class name, the import line, or the first argument, change the string in the call so the message reads Welcome to IJK TEC. Before you run the program, predict which part of the window will change and which parts will stay the same. Then explain, using the three parts of the work described in this article, why the button and the window structure do not need any new code.

Hints
  • Only the second argument of showMessageDialog controls the message text
  • The window and the OK button are produced by the method call, not by separate lines of your code
  • Compare the stages of the run: only the message stage should differ from the Hello World version

Key Takeaways

  • A GUI program opens its own window and talks to the user through it; a simple one can be written in only a few lines.
  • The showMessageDialog() method is a static method in the built-in JOptionPane class, and it creates the window, draws the message and OK button, and handles the OK click.
  • Because the method is static, it is called on the class name JOptionPane without creating an object first; the second argument supplies the message text.
  • The import line lets the program write the simple name JOptionPane instead of javax.swing.JOptionPane. It changes how the name is written, not what the class does.
  • When a GUI program misbehaves, check each stage in order (compiles and runs, window appears, message is correct, OK button exists, clicking OK ends the program) and investigate the first stage that fails.