问题描述
所以默认情况下,我没有在窗口框架上放置图像,我希望在我的应用程序运行时添加要放置在框架角上的图像。我浏览了论坛,看到了一堆根本没有帮助我的解决方案。我的程序运行没有错误,但图像没有显示..但是,当程序在 linux 中运行时,当我专注于我的应用程序时,主导航栏(顶部)确实设置了图像,但这不会发生在 MacOS 中.
我的代码:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
Image image = null;
URL url = null;
try {
url = new URL("https://www.multivutech.com/images/logo1.png");
image = ImageIO.read(url);
} catch (MalformedURLException ex) {
System.out.println("Malformed URL");
} catch (IOException iox) {
System.out.println("Can not load file");
}
panel.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
panel.setLayout(new FlowLayout());
frame.getContentPane().add(panel,BorderLayout.CENTER);
JLabel label = new JLabel("Hello World!",SwingConstants.CENTER);
panel.add(label);
frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Hello World Frame!");
frame.setIconImage(image);
frame.pack();
frame.setVisible(true);
frame.setSize(354,279);
解决方法
它在 Mac 上不起作用的原因是 Frame 不显示图标。
如果你添加了这个,那么你可以改变 Dock 中显示的图标:
Taskbar.getTaskbar().setIconImage(image);
这是一个基于您的代码的示例。
import java.awt.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class JFrameImageIconDemo {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Hello World Frame!");
frame.setSize(354,279);
URL url = new URL("https://www.multivutech.com/images/logo1.png");
Image image = ImageIO.read(url);
Taskbar.getTaskbar().setIconImage(image);
frame.setIconImage(image);
frame.setVisible(true);
}
}