JFrame

1. As in the AWT, starting point for graphical applications.

2. One of few Swing components that is built on an underlying "heavyweight" window.

3. Main differences in use compared to Frame:

4. JFrame Example: Source Code

This shows the steps required to imitate what you would get in the AWT if you popped up a simple Frame, set the layout manager to FlowLayout, and dropped three buttons into it.

JFrameExample.java (Download source code)

import java.awt.*;
import javax.swing.*;

public class JFrameExample {
  public static void main(String[] args) {
    WindowUtilities.setNativeLookAndFeel();
    JFrame f = new JFrame("This is a test");
    f.setSize(400, 150);
    Container content = f.getContentPane();
    content.setBackground(Color.white);
    content.setLayout(new FlowLayout()); 
    content.add(new JButton("Button 1"));
    content.add(new JButton("Button 2"));
    content.add(new JButton("Button 3"));
    f.addWindowListener(new ExitListener());
    f.setVisible(true);
  }
}
Note: also requires WindowUtilities.java, shown earlier.

ExitListener.java (Download source code)

import java.awt.*;
import java.awt.event.*;

public class ExitListener extends WindowAdapter {
  public void windowClosing(WindowEvent event) {
    System.exit(0);
  }
}

5. JFrame Example: Result

JFrameExample Output


This page is part of the Quick Swing Tutorial for AWT Programmers. © 1999 Marty Hall. All source code freely available for unrestricted use. Created for for work in the Research and Technology Development Center of the Johns Hopkins University Applied Physics Lab, for courses in the Johns Hopkins Part-Time MS Program in Computer Science, and for various industry seminars and Java short courses.