New to Java? We'll help you get started with our revised beginner's tutorial, or our free online textbook.


Get the latest Java books
h t t p : / /w w w . j a v a c o f f e e b r e a k . c o m /

Java Coffee Break

Menu



Learning Java

Articles
Author Profiles
Lessons
FAQ's
Books
Newsletter
Tutorials
Talk Java!

Using Java

Applets
JavaBeans
Servlets
Resources
Discuss Java


Looking for Java resources? Check out the Java Coffee Break directory!

Writing the Swing version

The code to generate an Swing-based application is actually little different from a purely AWT-based one. The changes between the SwingFrame example, and the AWTFrame example, are highlighted in bold. Figure 4 shows the application in action, with the default 'Metal' L&F.


SwingFrame.java

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

public class SwingFrame
{
  public static void main (String args[])
   throws Exception
  {
    JFrame  frame = new JFrame("Swing Demo");
    JLabel  label = new JLabel("Swing Version");
    JButton button = new JButton ("Click to close");
    button.addActionListener( new ActionListener() {
      public void actionPerformed(ActionEvent evt)
      {
        System.exit(0);
      }
    });

    // Get content pane
    Container pane = frame.getContentPane();

    // Set layout manager
    pane.setLayout( new FlowLayout() );

    // Add to pane
    pane.add( label  );
    pane.add( button );
    frame.pack();

    // Center the frame
    Toolkit toolkit = Toolkit.getDefaultToolkit();

    // Get the current screen size
    Dimension scrnsize = toolkit.getScreenSize();

    // Get the frame size
    Dimension framesize= frame.getSize();

    // Set X,Y location
    frame.setLocation ( (int) (scrnsize.getWidth()
                        - frame.getWidth() ) / 2 ,
                        (int) (scrnsize.getHeight()
                        - frame.getHeight()) / 2);

    frame.setVisible(true);
  }
}

Swing version
Figure 4- Swing Version

Wrapping it all up - Swing vs. AWT

Back to main


Copyright 1998, 1999, 2000 David Reilly

Privacy | Legal | Linking | Advertise!

Last updated: Monday, June 05, 2006