Advertisement

javax.swing——从今天开始探究javax.swing——编译和运行Swing程序

阅读量:

一、最初的试探

如何从命令行编译和运行Swing应用程序。需要按照如下步骤:

  • 安装最新版本的 Java SE 平台(如果您尚未安装)。
  • 创建一个使用 Swing 组件的程序。
  • 编译程序。
  • 运行程序。

1.1 安装最新版的Java SE平台

可以从http://www.oracle.com/technetwork/java/javase/downloads/index.html免费下载最新版本的 JDK 。

1.2 创建一个使用Swing组件的程序

一个位于包start中的HelloWorldSwing.java文件。

复制代码
 package start;

    
  
    
 /* * HelloWorldSwing.java requires no other files. 
    
  */
    
 import javax.swing.*;        
    
  
    
 public class HelloWorldSwing {
    
     /** * Create the GUI and show it.  For thread safety,
    
      * this method should be invoked from the
    
      * event-dispatching thread.
    
      */
    
     private static void createAndShowGUI() {
    
     //Create and set up the window.
    
     JFrame frame = new JFrame("HelloWorldSwing");
    
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
  
    
     //Add the ubiquitous "Hello World" label.
    
     JLabel label = new JLabel("Hello World");
    
     frame.getContentPane().add(label);
    
  
    
     //Display the window.
    
     frame.pack();
    
     frame.setVisible(true);
    
     }
    
  
    
     public static void main(String[] args) {
    
     //Schedule a job for the event-dispatching thread:
    
     //creating and showing this application's GUI.
    
     javax.swing.SwingUtilities.invokeLater(new Runnable() {
    
         public void run() {
    
             createAndShowGUI();
    
         }
    
     });
    
     }
    
 }
    
    
    
    

1.3 编译程序

要编译示例,可以从文件上方的HelloWorldSwing目录即包start:

javac start/HelloWorldSwing.java

也单从start目录中的文件[HelloWorldSwing.java](https://docs.oracle.com/javase/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java):

javac HelloWorldSwing.java

如果无法编译,可能就要使用最新版本的Java平台中的编译器。

1.4 运行程序

程序编译成功后,就可以运行了。从目录上面的start目录:

复制代码
    java start.HelloWorldSwing

如果要运行java文件,必须从包名开始,它会从代码的第一行识别。

运行结果:

全部评论 (0)

还没有任何评论哟~