Classes and Methods from the Java API

By Barry A. Burd

The Java code you see here uses several API classes and methods. The setTitle, setLayout, setDefaultCloseOperation, add, setSize, and setVisible methods all belong to the javax.swing.JFrame class.

Java code for defining a frame.

import java.awt.FlowLayout;

import javax.swing.JFrame;

import javax.swing.JButton;

@SuppressWarnings("serial")

public class SimpleFrame extends JFrame {

public SimpleFrame() {

setTitle("Don't click the button!");

setLayout(new FlowLayout());

setDefaultCloseOperation(EXIT_ON_CLOSE);

add(new JButton("Panic"));

setSize(300, 100);

setVisible(true);

}

}

Here’s a list of names used in the code:

  • setTitle: Calling setTitle puts words in the frame’s title bar. (The new SimpleFrame object is calling its own setTitle method.)
  • FlowLayout: An instance of the FlowLayout class positions objects on the frame in a centered, typewriter fashion. If the frame has only one button on it, that button is centered near the top of the frame. If the frame had eight buttons, five of them may be lined up in a row across the top of the frame and the remaining three would be centered along a second row.
  • setLayout: Calling setLayout puts the new FlowLayout object in charge of arranging components, such as buttons, on the frame. (The new SimpleFrame object is calling its own setLayout method.)
  • setDefaultCloseOperation: Calling setDefaultCloseOperation tells Java what to do when you click the little ×in the frame’s upper-right corner. (On a Mac, you click the little red circle in the frame’s upper-left corner.) Without this method call, the frame itself disappears, but the Java Virtual Machine (JVM) keeps running. To stop your program’s run, you have to perform one more step. (You may have to look for a Terminate option in Eclipse, IntelliJ IDEA, or NetBeans.)
  • Calling setDefaultCloseOperation(EXIT_ON_CLOSE) tells Java to shut itself down when you click the × in the frame’s upper-right corner. The alternatives to EXIT_ON_CLOSE are HIDE_ON_CLOSE, DISPOSE_ON_CLOSE, and, of course, DO_NOTHING_ON_CLOSE. Use one of these alternatives when your program has more work to do after the user closes your frame.
  • JButton: The JButton class lives in the javax.swing package. One of the class’s constructors takes a String instance (such as “Panic“) for its parameter. Calling this constructor makes that String instance into the label on the face of the new button.
  • add: The new SimpleFrame object calls its add method. Calling the add method places the button on the object’s surface (in this case, the surface of the frame).
  • setSize: The frame becomes 300 pixels wide and 100 pixels tall. (In the javax.swing package, whenever you specify two dimension numbers, the width number always comes before the height number.)
  • setVisible: When it’s first created, a new frame is invisible. But when the new frame calls setVisible(true), the frame appears on your computer screen.