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
: CallingsetTitle
puts words in the frame’s title bar. (The newSimpleFrame
object is calling its ownsetTitle
method.)FlowLayout
: An instance of theFlowLayout
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
: CallingsetLayout
puts the newFlowLayout
object in charge of arranging components, such as buttons, on the frame. (The newSimpleFrame
object is calling its ownsetLayout
method.)setDefaultCloseOperation
: CallingsetDefaultCloseOperation
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 toEXIT_ON_CLOSE
areHIDE_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
: TheJButton
class lives in thejavax.swing
package. One of the class’s constructors takes aString
instance (such as "Panic
") for its parameter. Calling this constructor makes thatString
instance into the label on the face of the new button.add
: The newSimpleFrame
object calls itsadd
method. Calling theadd
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 thejavax.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 callssetVisible(true)
, the frame appears on your computer screen.