【问题标题】:JOptionPanel.showMessageDialog doesn't show up when program is run through the .jar file当程序通过 .jar 文件运行时,JOptionPane.showMessageDialog 不显示
【发布时间】:2019-04-09 08:06:06
【问题描述】:

我做了一些搜索来寻找我的问题的答案,但没有找到任何与我的完全匹配的东西,也许我搜索的不够努力,但我是这个网站的新手。

所以我使用 NetBeans IDE 8.0.2,当我通过 IDE 运行我的程序时,一切正常。但是当我通过它的 Executable Jar 文件运行它时,我得到了前 2 个输入框,但最终的警报没有出现。

程序简单地从输入中获取 2 个名称(球员),然后从名为“teams.txt”的外部列表中为每个人分配一个在国际足联中使用的球队。我为我和我的室友制作了它,以便我们在玩 FIFA 19 时使用,我们想使用随机球队,但不想被 1-2 星级球队卡住。

public class Main {

public static void main(String[] args) {

    List<String> teams = new ArrayList<>();

    // Read file, then store each new line item in the ArrayList.
    try {
        Scanner s = new Scanner(new File("teams.txt"));

        while (s.hasNext()) {
            teams.add(s.nextLine());
        }
    } catch (FileNotFoundException ex) {
        System.out.println("File Not Found");
    }

    // Take user input from dialog box and store it in variables player1 and player2.
    String player1 = JOptionPane.showInputDialog("Player 1: Enter your name.");
    String player2 = JOptionPane.showInputDialog("Player 2: Enter your name.");
    //Print the values given in the Java console.
    System.out.println("Player 1: " + player1);
    System.out.println("Player 2: " + player2);

    // Random team generator within dialog box.
    Random r = new Random();
    String msg1 = player1 + ": " + teams.get(r.nextInt(teams.size()));
    String msg2 = player2 + ": " + teams.get(r.nextInt(teams.size()));
    Component frame = null;
    ImageIcon icon = new ImageIcon("icon2.png");
    JOptionPane.showMessageDialog(frame, msg1 + "\n" + msg2, "Fifa Team Picker", PLAIN_MESSAGE, icon);
}
}

【问题讨论】:

    标签: java file jar embedded-resource


    【解决方案1】:

    您不能将单个 .jar 文件条目作为文件读取,因为它们不是单独的文件。它们只是指示压缩数据的字节子序列。这意味着您的 Scanner 失败,并且您的 teams 集合为空,这反过来又导致 teams.get 引发异常。

    如果您在命令行上运行 .jar 文件,您可以自己看到这一点。这样的命令通常看起来像:java -jar myteamsproject.jar

    作为应用程序一部分的文件称为资源。您必须使用 Class 的 getResourcegetResourceAsStream 方法读取它:

    Scanner s = new Scanner(Main.class.getResourceAsStream("teams.txt"));
    

    同样,您必须将资源作为 URL 传递给 ImageIcon,而不是文件名:

    ImageIcon icon = new ImageIcon(Main.class.getResource("icon2.png"));
    

    当然,除非 team.txt 和 icon2.png 实际上在 .jar 文件中,否则上述行将不起作用。构建 .jar 文件后,您应该检查其内容并验证这些条目是否存在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-26
      • 2014-03-26
      • 2017-06-07
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      • 2012-07-13
      • 2020-01-23
      相关资源
      最近更新 更多