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: CallingsetTitleputs words in the frame’s title bar. (The newSimpleFrameobject is calling its ownsetTitlemethod.)FlowLayout: An instance of theFlowLayoutclass 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: CallingsetLayoutputs the newFlowLayoutobject in charge of arranging components, such as buttons, on the frame. (The newSimpleFrameobject is calling its ownsetLayoutmethod.)setDefaultCloseOperation: CallingsetDefaultCloseOperationtells 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_CLOSEareHIDE_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: TheJButtonclass lives in thejavax.swingpackage. One of the class’s constructors takes aStringinstance (such as "Panic") for its parameter. Calling this constructor makes thatStringinstance into the label on the face of the new button.add: The newSimpleFrameobject calls itsaddmethod. Calling theaddmethod 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.swingpackage, 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.


