JDK6.0的新特性之一:Desktop和SystemTray類

okone96發表於2007-01-10

在JDK6中 ,AWT新增加了兩個類:Desktop和SystemTray,前者可以用來開啟系統預設瀏覽器瀏覽指定的URL,開啟系統預設郵件客戶端給指定的郵箱發郵件,用預設應用程式開啟或編輯檔案(比如,用記事本開啟以txt為字尾名的檔案),用系統預設的印表機列印文件;後者可以用來在系統托盤區建立一個托盤程式.下面程式碼演示了Desktop和SystemTray的用法.

/**
*
* @author chinajash
*/
public class DesktopTray {
private static Desktop desktop;
private static SystemTray st;
private static PopupMenu pm;
public static void main(String[] args) {
if(Desktop.isDesktopSupported()){//判斷當前平臺是否支援Desktop類
desktop = Desktop.getDesktop();
}
if(SystemTray.isSupported()){//判斷當前平臺是否支援系統托盤
st = SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage("netbeans.png");//定義托盤圖示的圖片
createPopupMenu();
TrayIcon ti = new TrayIcon(image, "Desktop Demo Tray", pm);
try {
st.add(ti);
} catch (AWTException ex) {
ex.printStackTrace();
}
}
}

public static void sendMail(String mail){
if(desktop!=null && desktop.isSupported(Desktop.Action.MAIL)){
try {
desktop.mail(new URI(mail));
} catch (IOException ex) {
ex.printStackTrace();
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
}
}

public static void openBrowser(String url){
if(desktop!=null && desktop.isSupported(Desktop.Action.BROWSE)){
try {
desktop.browse(new URI(url));
} catch (IOException ex) {
ex.printStackTrace();
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
}
}

public static void edit(){
if(desktop!=null && desktop.isSupported(Desktop.Action.EDIT)){
try {
File txtFile = new File("test.txt");
if(!txtFile.exists()){
txtFile.createNewFile();
}
desktop.edit(txtFile);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

public static void createPopupMenu(){
pm = new PopupMenu();
MenuItem openBrowser = new MenuItem("Open My Blog");
openBrowser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openBrowser("
");
}
});

MenuItem sendMail = new MenuItem("Send Mail to me");
sendMail.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendMail("
mailto:chinajash@yahoo.com.cn");
}
});

MenuItem edit = new MenuItem("Edit Text File");
sendMail.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
edit();
}
});

MenuItem exitMenu = new MenuItem("&Exit");
exitMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
pm.add(openBrowser);
pm.add(sendMail);
pm.add(edit);
pm.addSeparator();
pm.add(exitMenu);
}
}
http://blog.csdn.net/chinajash

如果在Windows中執行該程式,可以看到在系統托盤區有一個圖示,右擊該圖示會彈出一個選單,點選Open My Blog會開啟IE,並瀏覽"http://blog.csdn.net/chinajash";點選Send Mail to me會開啟Outlook Express給我發郵件;點選Edit Text File會開啟記事本編輯在程式中建立的檔案test.txt

[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/750220/viewspace-889297/,如需轉載,請註明出處,否則將追究法律責任。

相關文章