使用winRAR把java文件打包成exe文件
一、前期准备
为了能看到执行结果,先编写一个swing的程序, 类名 ButtonTest.java,包路径 com.test。
将 ButtonTest.java 保存在D盘根目录下
运行中输入cmd进入DOS,进入D盘根目录
C:\Documents and Settings\Administrator>d:
使用 javac -d 进行编译,将会在D盘根目录下生成一个com文件夹
D:\>javac -d .\ ButtonTest.java
使用 java 执行,看看是否成功
D:\>java com.test.ButtonTest
安装winRAR,例子中使用的是3.0版本。
二、制作EXE
1、回到windows窗口,来到D盘,使用鼠标右键点击com文件夹,选择winRAR的右键菜单 “添加到档案文件”
选项。
出现 档案文件名字和参数 对话框窗口
2、在 常规 选项卡中设置以下参数
档案文件名 中输入 ButtonTest
档案文件类型 中选择 ZIP
压缩方式 中选择 存储
存档选项 中选择 创建自释放格式档案文件
3、在 高级 选项卡中 选择 自解压选项(或 SFX选项)
4、出现 高级自释放选项 对话框窗口
1)在 常规 选项卡中设置以下参数
释放后运行 中输入 java
com.test.ButtonTest
2)在 模式 选项卡中设置以下参数
临时模式 中选择 解压到临文件夹
缄默模式 中选择 全部隐藏
覆盖方式 中选择 覆盖所有文件
选择 确定(高级自释放选项 对话框)
选择 确定(档案文件名字和参数 对话框)
三、执行EXE
这时在D盘下会生成一个 ButtonTest.exe 文件,点击执行即可。
注意:
如果出现 'javac' 不是内部或外部命令,也不是可运行的程序或批处理文件。 错误时。
请在系统环境变量 Path 中设置 java 的环境变量。相关连接 http://zhidao.baidu.com/question/1495912.html
用以上方式生成的 exe 文件,对运行环境有要求:
1、运行的机器上已经安装了j2sdk
2、系统环境变量 path 中已经设置了 java 的环境变量,也就是说可以执行 java
方法。
3、运行程序可能会用到第三方的jar包,需要使用 java -classpath
参数来执行。(对于java命令这里就不做详细解释了)
以下是 ButtonTest.java 源码
package com.test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonTest {
public static void main(String[] args) {
ButtonFrame frame = new
ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class ButtonFrame extends JFrame {
public ButtonFrame() {
setTitle("ButtonTest");
setSize(DEFAULT_WIDTH,
DEFAULT_HEIGHT);
// add panel to frame
ButtonPanel panel = new
ButtonPanel();
Container contentPane =
getContentPane();
contentPane.add(panel);
}
public static final int DEFAULT_WIDTH =
300;
public static final int DEFAULT_HEIGHT =
200;
}
class ButtonPanel extends JPanel {
public ButtonPanel() {
// create buttons 这里产生三个event
source object
JButton yellowButton = new
JButton("Yellow");
JButton blueButton = new
JButton("Blue");
JButton redButton = new
JButton("Red");
// add buttons to
panel
add(yellowButton);
add(blueButton);
add(redButton);
// create button
actions
ColorAction yellowAction = new
ColorAction(Color.YELLOW);
ColorAction blueAction = new
ColorAction(Color.BLUE);
ColorAction redAction = new
ColorAction(Color.RED);
// event source 注册listener
object
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
}
private class ColorAction implements
ActionListener {
public ColorAction(Color c)
{
backgroundColor
= c;
}
//ActionEvent
event定义了一个event object
public void
actionPerformed(ActionEvent event) {
setBackground(backgroundColor);
}
private Color
backgroundColor;
}
}