import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URI;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class DesktopDemo {
static Desktop desktop;
public static void main(String[] args) {
if(Desktop.isDesktopSupported()){
desktop = Desktop.getDesktop();
}else{
System.out.print("This OS isnot supported");
System.exit(1);
}
JMenuItem openItem = new JMenuItem("打开");
JMenuItem editItem = new JMenuItem("编辑");
JMenuItem printItem = new JMenuItem("打印");
JMenuItem browseToItem = new JMenuItem("Goto blog.csdn.com/youyigong");
JMenuItem mailToItem = new JMenuItem("Emil to me");
JMenu fileMenu = new JMenu("文件");
JMenu mailMenu = new JMenu("邮件");
JMenu browseMenu = new JMenu("Browse");
openItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){//approve:批准认可
try{
desktop.open(chooser.getSelectedFile().getAbsoluteFile());
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
fileMenu.add(openItem);
editItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){//approve:批准认可
try{
desktop.edit(chooser.getSelectedFile().getAbsoluteFile());
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
fileMenu.add(editItem);
printItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){//approve:批准认可
try{
desktop.print(chooser.getSelectedFile().getAbsoluteFile());
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
fileMenu.add(printItem);
browseToItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try{
URI browseURI = new URI("http://blog.csdn.com/youyigong");
desktop.browse(browseURI);
}catch(Exception ex){
ex.printStackTrace();
}
}
});
browseMenu.add(browseToItem);
mailToItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
URI mailURI = new URI("mailto:support@java.com");
desktop.mail(mailURI);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
});
mailMenu.add(mailToItem);
JMenuBar jMenuBar = new JMenuBar();
jMenuBar.add(fileMenu);
jMenuBar.add(mailMenu);
jMenuBar.add(browseMenu);
JFrame frame = new JFrame();
frame.setTitle("Desktop Helper Applications");
frame.setJMenuBar(jMenuBar);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,100);
frame.setVisible(true);
}
}