2011-05-27 182 views
3

我使用Eclipse在Java中创建了命令行应用程序。我创建了一个可运行的JAR,并明白如果我想运行它,我需要通过命令提示符来完成。有没有办法让.jar打开命令提示符并单击运行程序?为了阐明,该程序在Eclipse的控制台中工作,并运行通过命令提示符创建的.jar工程(即java -jar Minesweeper.jar)。当我点击.jar文件时,我只想执行它。为命令行创建可运行的JAR文件Java应用程序

回答

2

当试图运行命令行基本应用程序作为可运行jar文件时,我注意到了这个问题。如果您尝试执行创建和显示jframe等操作,它会正常工作。我唯一的建议是,如果你使用的是Windows,你可以使具有行的批处理文件:

java -jar nameofjar.jar 

名称的文件类似的run.bat,然后你可以双击这一点,它会运行命令行应用程序。除此之外,我不知道为什么这个问题出现在基于命令行输入的应用程序中。

编辑:

这是一种方法,使一个假命令提示符显示,如果你不能想出一个办法来得到真正的一个,从双击运行罐子。

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文件的方式可能会出错。

+0

这个_works_用于所有的意图和目的......我现在会保留这个问题一点,只是为了看看是否有任何运气。 坚持下去,这里有一个想法:有什么办法可以创建一个显示控制台输出的GUI类型的东西吗? – Salem 2011-05-27 03:24:38

+0

你可以制作一个jscrollpane并为它添加一个jtextarea。您可以修改jscrollpane和jtextarea属性,使其看起来像命令提示符,而不是使用像System.out.println()这样的语句打印到标准输出,请使用myTextArea.append(“some text \ n”);这会将文本打印到文本区域。 – MBU 2011-05-27 10:04:28

+0

你是我的英雄。作为一名Java新手,我一直在想这是否可能。 – Salem 2011-05-27 21:08:52

0

你在Windows上吗?

您是否尝试过创建一个快捷方式到您的jar文件? 桌面>右键单击>创建快捷方式> [指定您的jar文件的路径]

如果您确实有可运行jar,您应该可以通过单击或双击运行它。

+0

我只是再试一次。捷径起作用。 – 2011-05-27 02:58:12