如何实现在Java中实现把图片作为图标并显示在系统托盘中?下面展示做法:
首先我们应该把图片导入工程你的存储路径:
在这之后我们可以直接复制文件名并导入到程序语句中: private Image image = Toolkit.getDefaultToolkit().createImage("Chrysanthemum.jpg");
下面贴出代码:
package Test1; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.SystemTray; import java.awt.TrayIcon; import javax.swing.*; public class ActionEvent4 extends JFrame implements ActionListener { private Image image = Toolkit.getDefaultToolkit().createImage("Chrysanthemum.jpg");//这里你得//改一下 private TrayIcon tl = new TrayIcon(image); public ActionEvent4() throws AWTException { super( "单击了托盘图标" ); SystemTray.getSystemTray().add(tl); tl.addActionListener(this); tl.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { showView(); } }); } private void showView(){ ActionEvent4.this.setVisible(true); ActionEvent4.this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ActionEvent4.this.setSize(400, 300); } public static void main(String[] args) throws AWTException { // TODO Auto-generated method stub new ActionEvent4(); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if ( e.getSource() == tl ){ this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(400,300); } } }