Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 7 ■ WRITING A USER INTERFACE


code in this book is not optimized for speed, by the way. I just show you the basics. To teach you
everything about Swing, I'd have to write another (very likely larger) book.

A Basic Swing Application


Swing applications follow a fairly common flow. First, we create a JFrame object. The JFrame object is the
main window and holds all the other interface components (buttons, text fields, and so on).
So, let's write a Swing application. The JFrame class lets you create a window, put other components
in that window, and associate other windows with the first window. Consequently, creating a JFrame
object is often the first step to creating a Swing application. As usual in software development, other
ways exist, but we follow one common path, as shown in Listing 7-1.

Listing 7-1. The simplest possible Swing application

package com.apress.java7forabsolutebeginners.examples.swingdemo;

import java.awt.Dimension;

import javax.swing.JFrame;

public class SwingDemo {

private JFrame frame = new JFrame("SwingDemo");

private void createAndShowGUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(200, 200));
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
SwingDemo swingDemo = new SwingDemo();
swingDemo.createAndShowGUI();
}
}

Before we go any further, Figure 7-1 shows our simple application.
Free download pdf