java - 为命令行 Java 应用程序创建可运行的 JAR 文件

标签 java eclipse

我使用 Eclipse 在 Java 中创建了一个命令行应用程序。我已经创建了一个可运行的 JAR,并且知道如果我想运行它,我需要通过命令提示符来执行。有没有办法让 .jar 打开命令提示符并在单击时运行程序?

编辑:澄清一下,该程序在 Eclipse 的控制台中运行,并且运行我通过命令提示符创建的 .jar 运行(即 java -jar Minesweeper.jar) .我只是希望它在我单击 .jar 文件时像那样执行。

最佳答案

我在尝试将命令行基础应用程序作为可运行的 jar 文件运行时注意到了这个问题。如果您尝试执行创建和显示 jframe 之类的操作,它会很好地工作。我唯一的建议是,如果你在 Windows 上,你可以制作一个包含以下行的批处理文件:

java -jar nameofjar.jar

将文件命名为 run.bat 之类的名称,然后您可以双击它,它将运行命令行应用程序。除此之外,我不确定为什么基于命令行输入的应用程序会出现此问题。

编辑:

如果您无法找到一种通过双击 jar 来运行真实的命令提示符的方法,那么这里有一种方法可以显示伪造的命令提示符。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Rectangle;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;


public class FakeCommandPrompt {

private JTextArea myTextArea;
private JScrollPane scrollPane;
private JFrame mainFrame;

/**
 * Setup the fake command prompt.
 */
public FakeCommandPrompt()
{
    mainFrame = new JFrame();
    mainFrame.setBounds(new Rectangle(new Dimension(500, 400)));
    mainFrame.setBackground(Color.BLACK);

    myTextArea = new JTextArea();
    myTextArea.setBackground(Color.BLACK);
    myTextArea.setForeground(Color.WHITE);
    myTextArea.setEditable(false);
    myTextArea.setMargin(new Insets(10, 10, 10, 10));

    scrollPane = new JScrollPane(myTextArea);
    scrollPane.setBackground(Color.BLACK);

    mainFrame.add(scrollPane);
    mainFrame.setVisible(true);
}

public void printToCommandPrompt(String text)
{
    // Append the new next to the command prompt
    // Add a new line at the end
    this.myTextArea.append(text + "\n");
}

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    // Create and instance of the fake command prompt.
    FakeCommandPrompt commandPrompt = new FakeCommandPrompt();

    // Prints 0 -> 5 on the fake command prompt.
    for (int i = 0; i <= 5; i++)
    {
        commandPrompt.printToCommandPrompt(String.valueOf(i));
    }
}

}

另外,您能告诉我您用来创建可运行 jar 文件的步骤吗?上面的代码应该通过双击 jar 文件来运行。如果没有,那么您创建 jar 文件的方式可能有问题。

关于java - 为命令行 Java 应用程序创建可运行的 JAR 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6147270/

相关文章:

java - 使用带有 MySQL DB 的 Java 桌面应用程序完成后如何创建安装程序?

Java:保存递归本地计数器的值

c - 使用 Eclipse CDT 调试 Linux 内核时出现 “No source available 0x”

eclipse - 将 Jetty 安装到 Eclipse 中

java - 测试 java 中的预期编译时错误

java - 在 Beanshell 中获取 RFC1123_time (使用 JMeter)

java - 使用耳内反射改变静态场

java - 如何调用使用可能未初始化的数组作为参数的方法?

javax.validation.Validator 排除某些字段

java - Eclipse警告: Cannot be null?