Extending the JFrame Class

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

Sure. Like most classes, the JFrame class can be extended.

Extending the JFrame Class

a Myframe object

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.

QUESTION 11:

(Review :) Where must super( title ) appear in the constructor?