下面通过一个例子来说明,这个例子包括2个java文件和一个mf文件:
文件1:frame1.java
package testjar;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class frame1 extends jframe {
jpanel contentpane;
borderlayout borderlayout1 = new borderlayout();
//construct the frame
public frame1() {
enableevents(awtevent.window_event_mask);
try {
jbinit();
}
catch(exception e) {
e.printstacktrace();
}
}
//component initialization
private void jbinit() throws exception {
contentpane = (jpanel) this.getcontentpane();
contentpane.setlayout(borderlayout1);
this.setsize(new dimension(400, 300));
this.settitle("frame title");
}
//overridden so we can exit when window is closed
protected void processwindowevent(windowevent e) {
super.processwindowevent(e);
if (e.getid() == windowevent.window_closing) {
system.exit(0);
}
}
}
文件2:app.java
package testjar;
import javax.swing.uimanager;
import java.awt.*;
public class app {
boolean packframe = false;
//construct the application
public app() {
frame1 frame = new frame1();
//validate frames that have preset sizes
//pack frames that have useful preferred size info, e.g. from their layout
if (packframe) {
frame.pack();
}
else {
frame.validate();
}
//center the window
dimension screensize = toolkit.getdefaulttoolkit().getscreensize();
dimension framesize = frame.getsize();
if (framesize.height > screensize.height) {
framesize.height = screensize.height;
}
if (framesize.width > screensize.width) {
framesize.width = screensize.width;
}
frame.setlocation((screensize.width - framesize.width) / 2, (screensize.height - framesize.height) / 2);
frame.setvisible(true);
}
//main method
public static void main(string[] args) {
try {
uimanager.setlookandfeel(uimanager.getsystemlookandfeelclassname());
}
catch(exception e) {
e.printstacktrace();
}
new app();
}
}
文件3:manif.mf
main-class: testjar.app
复制上述的三个文件到一个目录中,用命令行进入这个目录并执行 javac -d . *.java,此时会编译生成class文件,然后执行 jar -cvfm te.jar manif.mf testjar,应该回生成一个名为te.jar的jar文件,双击它,就可以看到效果了!
新闻热点
疑难解答