主题:Swing 实现截图小软件 (六)

13年前

既然 sdtm1016 兄 给出新的建议,那我们就继续完善下 SnapShoot

 

按 sdtm1016 兄的需求,这次再增加三个功能:

 

1. 修改文件选择窗口的默认目录为系统桌面,且给定默认文件名。


2. 增加托盘功能,且程序运行时,不自动显示软件窗口。


3. 增加系统热键功能,即:不管程序当前有没有获得焦点,均可以保持键盘快捷键的监听,实现快捷功能。

 

 

功能一: 修改文件选择窗口的默认目录为系统桌面,且给定默认文件名。

 

对于在当前用户的系统桌面目录的取得,Java API 已经有提供了:

Java代码 复制代码
  1. //得到当前用户的桌面目录   
  2. File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();  

 

那么我们设定文件选择窗口的默认选中文件为  用户桌面目录下的 save.png :

Java代码 复制代码
  1. JFileChooser chooser = new JFileChooser();   
  2. File selectedFile = new File(FileSystemView.getFileSystemView().getHomeDirectory(), "save.png");   
  3. //设置默认选中文件   
  4. chooser.setSelectedFile(selectedFile);  

 

功能一完成。

 

 

 

功能二:增加托盘功能,且程序运行时,不自动显示软件窗口。

 

在 JDK6.0 中,也提供了对系统托盘的操作。  本例关于加入系统托盘的代码:

Java代码 复制代码
  1. /**  
  2.  * 加入系统托盘  
  3.  */  
  4. private void addSystemTray() {   
  5.     //修改窗口关闭和最小化事件   
  6.     this.addWindowListener(new WindowAdapter() {   
  7.         public void windowClosed(WindowEvent e) {   
  8.             SnapShoot.this.setVisible(false);   
  9.         }   
  10.            
  11.         public void windowIconified(WindowEvent e) {   
  12.             SnapShoot.this.setVisible(false);   
  13.         }   
  14.     });   
  15.        
  16.     if (SystemTray.isSupported()) {   
  17.            
  18.         SystemTray tray = SystemTray.getSystemTray();   
  19.            
  20.         // 为这个托盘加一个弹出菜单   
  21.         final PopupMenu popup = new PopupMenu();   
  22.         MenuItem item = new MenuItem("open  ctrl + shift + o");   
  23.         MenuItem exit = new MenuItem("exit");   
  24.         popup.add(item);   
  25.         popup.add(exit);   
  26.            
  27.         item.addActionListener(new ActionListener() {   
  28.             public void actionPerformed(ActionEvent e) {   
  29.                 SnapShoot.this.setVisible(true);   
  30.             }   
  31.         });   
  32.            
  33.         exit.addActionListener(new ActionListener() {   
  34.             public void actionPerformed(ActionEvent e) {   
  35.                 //清除系统热键   
  36.                 JIntellitype.getInstance().cleanUp();   
  37.                 System.exit(1);   
  38.             }   
  39.         });   
  40.            
  41.         // 为这个托盘加一个提示信息   
  42.         Image scaleLogo = ((BufferedImage)logo).getScaledInstance(1616, Image.SCALE_FAST);   
  43.         TrayIcon trayIcon = new TrayIcon(scaleLogo, "屏幕截图小软件: SnapShoot\n作者:pengranxiang", popup);   
  44.            
  45.         try {   
  46.             tray.add(trayIcon);   
  47.         } catch (AWTException e) {   
  48.             System.err.println("无法向这个托盘添加新项: " + e);   
  49.         }   
  50.     } else {   
  51.         System.err.println("无法使用系统托盘!");   
  52.     }   
  53. }