文档

Java™ 教程-Java Tutorials 中文版
编译和运行 Swing 程序
Trail: Creating a GUI With JFC/Swing
Lesson: Getting Started with Swing

编译和运行 Swing 程序

This section explains how to compile and run a Swing application from the command line. For information on compiling and running a Swing application using NetBeans IDE, see Running Tutorial Examples in NetBeans IDE. The compilation instructions work for all Swing programs — applets, as well as applications. Here are the steps you need to follow:

Install the Latest Release of the Java SE Platform

You can download the latest release of the JDK for free from http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Create a Program That Uses Swing Components

You can use a simple program we provide, called HelloWorldSwing, that brings up the GUI shown in the figure below. The program is in a single file,HelloWorldSwing.java. When you save this file, you must match the spelling and capitalization of its name exactly.

The HelloWorldSwing.java example, like all of our Swing tutorial examples, is created inside a package. If you look at the source code, you see the following line at the beginning of the file:

package start;

This means you must put the HelloWorldSwing.java file inside of a start directory. You compile and run the example from the directory above the start directory. The tutorial examples from the Using Swing Components lesson are inside of a components package and the examples from the Writing Event Listeners lesson are inside a events package, and so on. For more information, you might want to see the Packages lesson.

Screen shot of HelloWorldSwing application

Compile the Program

Your next step is to compile the program. To compile the example, from the directory above the HelloWorldSwing.java file:

javac start/HelloWorldSwing.java

If you prefer, you may compile the example from within the start directory:

javac HelloWorldSwing.java

but you must remember to leave the start directory to execute the program.

If you are unable to compile, make sure you are using the compiler in a recent release of the Java platform. You can verify the version of your compiler or Java Runtime Environment (JRE) using these commands

javac -version
java -version

Once you've updated your JDK, you should be able to use the programs in this trail without changes. Another common mistake is installing the JRE and not the full Java Development Kit (JDK) needed to compile these programs. Refer to the Getting Started trail to help you solve any compiling problems you encounter. Another resource is the Troubleshooting Guide for Java™ SE 6 Desktop Technologies.

运行程序

After you compile the program successfully, you can run it. From the directory above the start directory:

java start.HelloWorldSwing

Previous page: About the JFC and Swing
Next page: Learning Swing with the NetBeans IDE