如何在导出 jar 时为我的 jframe 设置图标而不必将图标放在桌面上?

How do I set the icon for my jframe without having to put the icon on my desktop when exporting the jar?

我想将 java 游戏的图标设置为名为 lgico.png 的图标,但是当我使用时:

static ImageIcon icon = new ImageIcon("lgico.png");
public Window(int width, int height, String title, Game game) {
    frame.setIconImage(icon.getImage());
}

我创建并放在桌面上的jar文件没有图标。

这是我的 window class 的全部内容:

package com.teto.main;
import java.awt.Canvas;
import java.awt.Cursor;
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class Window extends Canvas {
    private static final long serialVersionUID = 5486926782194361510L;
    static ImageIcon icon = new ImageIcon("lgico.png");
    Cursor csr = new Cursor(Cursor.CROSSHAIR_CURSOR);
    public Window(int width, int height, String title, Game game) {
        JFrame frame = new JFrame(title);
        frame.setPreferredSize(new Dimension(width, height));
        frame.setMaximumSize(new Dimension(width, height));
        frame.setMinimumSize(new Dimension(width, height));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.add(game);
        frame.setVisible(true);
        frame.setIconImage(icon.getImage());
        frame.setCursor(csr);
        game.start();
    }
}

我曾多次尝试在此站点上寻找解决方案,但都遇到了 NullPointerException 并且我的程序是一个没有任何内容的白屏。

由于我的母语不是英语,如果我试图表达的内容看起来不是很清楚,我深表歉意。

  1. 不要扩展 Canvas。您没有向 Canvas class 添加功能,因此没有理由扩展它。

  2. 不要打电话给你的 class Window。这是一个具有该名称的 AWT class。 Class 名称应该是描述性的。

  3. 如果您使用的是 jar 文件,那么您可能需要将图像作为资源加载:

这是一个基本示例:

import javax.swing.*;
import java.net.*;

class FrameIconFromMain
{
    public static void main(String[] args)
    {
        Runnable r = new Runnable()
        {
            public void run()
            {
                JFrame f = new JFrame("Frame with icon");
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

                String imageName = "dukewavered.gif";
                URL imageUrl = f.getClass().getResource(imageName);

                if (imageUrl == null)
                {
                    System.out.println("imageUrl not found using default classloader!");
                    imageUrl = Thread.currentThread().getContextClassLoader().getResource(imageName);
                }

                ImageIcon icon = new ImageIcon( imageUrl );
                f.setIconImage( icon.getImage() );
                f.setSize(400,300);
                f.setLocationRelativeTo( null );
                f.setVisible( true );
            }
        };

        SwingUtilities.invokeLater(r);
    }
}