Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 314|回复: 0

[Swing学习]Windows系统托盘图标实践(Swing)

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-10-29 23:55:55 | 显示全部楼层 |阅读模式
    下面例子同样是用trayicon-1.7.9b,Swing界面的托盘图标的一些特性,请参阅源码中的实例。
    先看"Hello World!"程序:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;

    public class TrayIconTest extends JFrame{
            
              JLabel lab=new JLabel("Hello World!!!");
          
              public TrayIconTest(){
                 getContentPane().add(lab);
                 setSize(400,300);
                 addWindowListener(new MywindowListener());
                  
              }
               
              class MywindowListener extends WindowAdapter{
                         public void windowClosing(WindowEvent e){
                                  System.exit(0);
                         }
              }

              public static void main(String[] args){
                          TrayIconTest test=new TrayIconTest();
                          test.show();
              }
    }

       下面是加了托盘图标后的程序(运行时要用的图像、包等请下载我的文件夹,
    程序仅供参考):

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.border.*;

    import com.jeans.trayicon.*;  
      
       

       
       

       
      
        // Demo app for Java Tray Icon
    public class SwingTrayIcon extends JFrame {     
                
       protected WindowsTrayIcon icon;
               JLabel lab=new JLabel("Hello World!!!");

               public SwingTrayIcon() throws TrayIconException, InterruptedException {
                     super("SwingTrayIcon");
             WindowsTrayIcon.setWindowsMessageCallback(new WindowsMessageCallback());
                     setIconImage(loadImage("Duke16.gif"));
                      
                     getContentPane().add(lab);
                     Image france = loadImage("Duke16.gif"); //装载图像
                           icon = new WindowsTrayIcon(france, 16, 16);//托盘图标
                           icon.setToolTipText("Hello");//设置托图标的工具提示
                           icon.setPopup(makePopup());//给托盘图标加弹出菜单
                           TestMouseListener mouse = new TestMouseListener();
                           icon.addMouseListener(mouse);//双击托盘图标的动作
                           icon.setVisible(true);//使托盘图标可见。
                           WindowsTrayIcon.keepAlive();
                           addWindowListener(new WindowClosingListener());//点窗口的关闭按钮时隐藏窗口
                           pack();
             }

             public TrayIconPopup makePopup() {//构造弹出菜单
                     TrayIconPopup popup = new TrayIconPopup();
                     TrayIconPopupSimpleItem item = new TrayIconPopupSimpleItem("&Show");
                     item.setDefault(true);
                     // Each menu item can have it"s own ActionListener
                     item.addActionListener(new RestoreListener());
                     popup.addMenuItem(item);
                     item = new TrayIconPopupSimpleItem("&About");
                     item.addActionListener(new AboutListener());
                     popup.addMenuItem(item);


                     popup.addMenuItem(new TrayIconPopupSeparator());
                     // Add exit item
                    item = new TrayIconPopupSimpleItem("E&xit");
                    item.addActionListener(new ExitListener());
                    popup.addMenuItem(item);
                    return popup;
           }


            // Load a gif image (used for loading the 16x16 icon gifs)
           public static Image loadImage(String fileName) {
                 return Toolkit.getDefaultToolkit().getImage("demo"+File.separator+"images"+File.separator+fileName);
          }

             // Use native windows look & feel
             public static void setLookAndFeel() {
                    try {
                          UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                    } catch (Exception ex) {}
             }     

            // 主函数
            public static void main(String[] args) {      
                 try {
                       setLookAndFeel();
                       TR.load("demo"+File.separator+"swing"+File.separator+"menu.eng");
                       String appName = "SwingTray";
                       long result = WindowsTrayIcon.sendWindowsMessage(appName, 1234);
                       if (result != -1) {
                                System.out.println("[Already running other instance of "+appName+" (returns: "+result+")].");
                                return;
                       }
                       // Init the Tray Icon library given the name for the hidden window
                            WindowsTrayIcon.initTrayIcon(appName);
                            SwingTrayIcon tray = new SwingTrayIcon();
                            SwingTrayIcon.centerDialog(tray);
                            tray.setSize(400,300);
                            tray.setVisible(true);
              } catch (TrayIconException e) {
                            System.out.println("Error: "+e.getMessage());
              } catch (IOException e) {
                            System.out.println("Error: "+e.getMessage());
              } catch (InterruptedException e) { }
         }


             // 在屏幕中央的对话框
             public static void centerDialog(Window frame) {
                     Dimension dialogSize = frame.getSize();
                     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                     frame.setLocation(screenSize.width/2 - dialogSize.width/2,
                                 screenSize.height/2 - dialogSize.height/2);
             }         


             private class WindowsMessageCallback implements TrayIconCallback {
                 public int callback(int param) {
                    System.out.println("[Other instance started (parameter: "+param+")].");
                    setVisible(true); toFront(); requestFocus();
                       // Return integer value to other process
                    return 4321;
               }
             }

           private class ExitListener implements ActionListener {
                      public void actionPerformed(ActionEvent evt) {
                              doExit();
                      }
           }

       
            

          public class WindowClosingListener extends WindowAdapter {//隐藏窗口
               public void windowClosing(WindowEvent e) {
                      setVisible(false);
              }
          }



          public void doExit() {
                    WindowsTrayIcon.cleanUp();
                    System.exit(0);
          }


             // Callback listener handles about button
             private class AboutListener implements ActionListener {

                           public void actionPerformed(ActionEvent evt) {
                              System.out.println("[About selected].");
                              // TestTrayIcon.this instead of this$0 for Java 1.3 compatibility
                              AboutBox box = new AboutBox(SwingTrayIcon.this);
                              centerDialog(box);
                              box.setVisible(true);
                            }
             }


             // Callback listener handles restore (click left on any icon / show popup menu)
             private class RestoreListener implements ActionListener {
                            public void actionPerformed(ActionEvent evt) {
                                 setVisible(true);
                                 toFront(); requestFocus();
                            }
             }



          
             // 鼠标双击事件
             public class TestMouseListener extends MouseAdapter {
                      public void mousePressed(MouseEvent evt) {
                            if ((evt.getModifiers() & MouseEvent.BUTTON1_MASK) != 0 && evt.getClickCount() == 2) {
                                         setVisible(true);
                            }
                        }
           }
    }

            // Stupid about box for demo app
            class AboutBox extends JDialog {
                 // Create new about box given parent frame
                 public AboutBox(JFrame parent)  {
                 // Make modal dialog given parent and title
                 super(parent, "About TrayIcon", true);
                 // Layout stuff
                    JPanel panel = new JPanel();
                    panel.setLayout(new BorderLayout(3,3));
                    JPanel txt = new JPanel();
                    txt.setLayout(new GridLayout(0,1));
                    txt.add(new JLabel("TrayIcon version: "+WindowsTrayIcon.TRAY_VERSION));
                    txt.add(new JLabel("OS version: "+WindowsTrayIcon.getWindowsVersionString()));
                    txt.add(new JLabel("Written by Jan Struyf <Jan.Struyf@cs.kuleuven.ac.be>"));
                    panel.add(txt, BorderLayout.CENTER);
                    JPanel buttons = new JPanel();
                    buttons.setLayout(new FlowLayout());
                    JButton button = new JButton("OK");
                    buttons.add(button, BorderLayout.CENTER);
                    panel.add(buttons, BorderLayout.SOUTH);
                    // Close listeners for OK button and window button
                    button.addActionListener(new CloseListener());
                    addWindowListener(new CloseWindowListener());
                    panel.setBorder(new EmptyBorder(4,4,4,4));
                    setContentPane(panel);
                    pack();
         }
             
            private class CloseListener implements ActionListener {
                        public void actionPerformed(ActionEvent evt) {
                            dispose();
                        }
       }

             // Close listener for windows button
             private class CloseWindowListener extends WindowAdapter {

                                public void windowClosing(WindowEvent evt) {
                                  dispose();
                                }
              }
    }  

      
      
       
       

         
       

         
       
      


                            function TempSave(ElementID)
                            {
                                    CommentsPersistDiv.setAttribute("CommentContent",document.getElementById(ElementID).value);
                                    CommentsPersistDiv.save("CommentXMLStore");
                            }
                            function Restore(ElementID)
                            {
                                    CommentsPersistDiv.load("CommentXMLStore");
                                    document.getElementById(ElementID).value=CommentsPersistDiv.getAttribute("CommentContent");
                            }
                   
                      











    源码下载:http://file.javaxxz.com/2014/10/29/235555265.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-5-18 19:29 , Processed in 0.384843 second(s), 46 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表