Sure. Like most classes,
the JFrame
class can be extended.
JFrame
Class
To write a GUI application, extend the JFrame
class.
Add GUI components to the extended class.
Here is a program that does that.
import java.awt.*; import javax.swing.*; class MyFrame extends JFrame { JPanel panel; JLabel label; // constructor MyFrame( String title ) { super( title ); // invoke the JFrame constructor setSize( 150, 100 ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setLayout( new FlowLayout() ); // set the layout manager label = new JLabel("Hello Swing!"); // construct a JLabel add( label ); // add the label to the JFrame } } public class TestFrame2 { public static void main ( String[] args ) { MyFrame frame = new MyFrame("Hello"); // construct a MyFrame object frame.setVisible( true ); // ask it to become visible } }
The new class is called MyFrame
and it is based
on JFrame
.
Exactly how a container arranges the components it contains
is determined by a layout manager.
The layout manager for this frame is set to FlowLayout
using the setLayout()
method.
(There will be more on this in the next chapter.)
The frame holds a GUI component, a JLabel
which displays the words "Hello Swing!" .
The JLabel
is added to the frame using
the add()
method.
The main()
method in this application does nothing more than
construct a MyFrame
object and set it visible.
(Review :) Where must super( title )
appear in the constructor?