windows中双击jar文件即可运行写法

下面通过一个例子来说明,这个例子包括2个java文件和一个mf文件:

文件1:Frame1.java

 1package testjar; 
 2
 3import java.awt.*;   
 4import java.awt.event.*;   
 5import javax.swing.*; 
 6
 7public class Frame1 extends JFrame {   
 8JPanel contentPane;   
 9BorderLayout borderLayout1 = new BorderLayout(); 
10
11//Construct the frame   
12public Frame1() {   
13enableEvents(AWTEvent.WINDOW_EVENT_MASK);   
14try {   
15jbInit();   
16}   
17catch(Exception e) {   
18e.printStackTrace();   
19}   
20} 
21
22//Component initialization   
23private void jbInit() throws Exception {   
24contentPane = (JPanel) this.getContentPane();   
25contentPane.setLayout(borderLayout1);   
26this.setSize(new Dimension(400, 300));   
27this.setTitle("Frame Title");   
28} 
29
30//Overridden so we can exit when window is closed   
31protected void processWindowEvent(WindowEvent e) {   
32super.processWindowEvent(e);   
33if (e.getID() == WindowEvent.WINDOW_CLOSING) {   
34System.exit(0);   
35}   
36}   
37} 

文件2:App.java

 1package testjar; 
 2
 3import javax.swing.UIManager;   
 4import java.awt.*; 
 5
 6public class App {   
 7boolean packFrame = false; 
 8
 9//Construct the application   
10public App() {   
11Frame1 frame = new Frame1();   
12//Validate frames that have preset sizes   
13//Pack frames that have useful preferred size info, e.g. from their layout   
14if (packFrame) {   
15frame.pack();   
16}   
17else {   
18frame.validate();   
19}   
20//Center the window   
21Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();   
22Dimension frameSize = frame.getSize();   
23if (frameSize.height > screenSize.height) {   
24frameSize.height = screenSize.height;   
25}   
26if (frameSize.width > screenSize.width) {   
27frameSize.width = screenSize.width;   
28}   
29frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);   
30frame.setVisible(true);   
31} 
32
33//Main method   
34public static void main(String[] args) {   
35try {   
36UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());   
37}   
38catch(Exception e) {   
39e.printStackTrace();   
40}   
41new App();   
42}   
43} 

文件3:manif.mf

Main-Class: testjar.App

复制上述的三个文件到一个目录中,用命令行进入这个目录并执行 javac -d . *.java,此时会编译生成class文件,然后执行 jar -cvfm te.jar manif.mf testjar,应该回生成一个名为te.jar的jar文件,双击它,就可以看到效果了!

Published At
Categories with Web编程
Tagged with
comments powered by Disqus