如何为JFrame窗口和托盘设置图标

我想在窗口中显示自己的图标而不是Java杯。

JFrame的屏幕截图

同样,当最小化时,我想显示我自己的图像。 我怎么能这样做?

我应该在哪里相对于源文件定位我的图像?

[UPDATE]

我试过但没有运气

TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().createImage("image/accounting.gif")); //setIconImage(); SystemTray tray = SystemTray.getSystemTray(); try { tray.add(trayIcon); } catch (AWTException e) { System.out.println("TrayIcon could not be added."); } 

我也试过了

 TrayIcon trayIcon = new TrayIcon(createImage("images/bulb.gif", "tray icon")); 

但是严重怀疑createImage(即使它是Object也不知道要导入什么。

问候,

关于您的TrayIcon问题,您可以参考下面的解决方案:

 public static void createSystemTrayIcon() { if (SystemTray.isSupported()) { SystemTray tray = SystemTray.getSystemTray(); Image image = Toolkit.getDefaultToolkit().getImage( System.getenv("MY_PROGRAM_HOME") + "game.ico" ); PopupMenu popup = new PopupMenu(); final MenuItem menuExit = new MenuItem("Quit"); MouseListener mouseListener = new MouseListener() { public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} }; ActionListener exitListener = new ActionListener() { public void actionPerformed(ActionEvent e) { Runtime r = Runtime.getRuntime(); System.out.println("Exiting..."); r.exit(0); } }; menuExit.addActionListener(exitListener); popup.add(menuExit); final TrayIcon trayIcon = new TrayIcon(image, "My program", popup); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { trayIcon.displayMessage( "My program ", "version: blahblah", TrayIcon.MessageType.INFO ); } }; trayIcon.setImageAutoSize(true); trayIcon.addActionListener(actionListener); trayIcon.addMouseListener(mouseListener); try { tray.add(trayIcon); } catch (AWTException e) { System.err.println("TrayIcon could not be added."); } } else { // System Tray is not supported } } 

使用JFrame.setIconImage()

使用setIconImages()的示例:(同样适用于setIconImage())

 public MyFrame() { initComponents(); //Added by Netbeans List icons = new ArrayList(); icons.add(new ImageIcon(getClass().getResource("/com/example/icons/16/app.png")).getImage()); icons.add(new ImageIcon(getClass().getResource("/com/example/icons/32/app.png")).getImage()); this.setIconImages(icons); } 

线索是使用“getImage()”来返回Image(因为ImageIcon不能直接在setIconImages()中使用)。

我还没有写过托盘图标,但最后我发现了设置jframe图标的主要问题。 这是我的代码。 它类似于其他代码,但这里有一些事情要记住游戏。

  this.setIconImage(new ImageIcon(getClass().getResource("Icon.png")).getImage()); 

1)将此代码放在jframe WindowOpened事件中

2)将Image放在主文件夹中,例如,创建所有表单和java文件

 src\ myproject\ myFrame.form src\ myproject\ myFrame.java src\ myproject\ OtherFrame.form src\ myproject\ OtherFrame.java src\ myproject\ Icon.png 

3)最重要的是文件名是区分大小写的,icon.png不起作用,但Icon.png。

这样,即使在最终构建项目之后,您的图标也会存在。