top
Loading...
JDK6.0新特性:Desktop和SystemTray類
在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("http://blog.csdn.net/chinajash");
}
});

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);
}
}

如果在Windows中運行該程序,可以看到在系統托盤區有一個圖標,右擊該圖標會彈出一個菜單,點擊Open My Blog會打開IE,并瀏覽我設定的BLOG地址;點擊Send Mail to me會打開Outlook Express給我發郵件;點擊Edit Text File會打開記事本編輯在程序中創建的文件test.txt。

作者:http://www.zhujiangroad.com
來源:http://www.zhujiangroad.com
北斗有巢氏 有巢氏北斗