`
xiaoer_1982
  • 浏览: 1816121 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

Java6学习笔记50——超文本链接

阅读更多

Desktop类既可以打开网页,也可以打开mailto:fred@example.com这样的邮箱地址,都是启动操作系统默认的浏览器或客户端。

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.BoxLayout;
import javax.swing.Box;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.awt.Container;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Desktop;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class BrowserDemo extends JFrame implements ActionListener {
public static void main(String arg[]) {
new BrowserDemo();
}
public BrowserDemo() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
} );
buildFrame();
setLocation(250,150);
setVisible(true);
}
private void buildFrame() {
JButton button;
Container pane = getContentPane();
pane.setLayout(new BoxLayout(pane,BoxLayout.Y_AXIS));
pane.add(Box.createRigidArea(new Dimension(100,10)));
button = new JButton("Google");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
button.addActionListener(this);
add(button);
button = new JButton("VTC");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
button.addActionListener(this);
add(button);
button = new JButton("Drudge");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
button.addActionListener(this);
add(button);
button = new JButton("Yahoo");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
button.addActionListener(this);
add(button);
button = new JButton("Amazon");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
button.addActionListener(this);
add(button);
pane.add(Box.createRigidArea(new Dimension(100,10)));
pack();
}
public void actionPerformed(ActionEvent e) {
String uriString = null;
if(!Desktop.isDesktopSupported()) {
System.out.println("Browser launching not supported.");
return;
}
Desktop desktop = Desktop.getDesktop(); //用来打开系统默认浏览器浏览指定的URL
String selection = e.getActionCommand();
if(selection.equals("Google")) {
uriString = "http://www.google.com";
} else if(selection.equals("VTC")) {
uriString = "http://www.vtc.com";
} else if(selection.equals("Drudge")) {
uriString = "http://drudgereport.com";
} else if(selection.equals("Yahoo")) {
uriString = "http://www.yahoo.com";
} else if(selection.equals("Amazon")) {
uriString = "http://www.amazon.com";
}
try {
URI uri = new URI(uriString);//转换为URI,通用资源标识符
desktop.browse(uri);//打开默认浏览器
} catch(URISyntaxException use) {//处理两个异常
System.out.println("URI Syntax exception");
} catch(IOException ioe) {
System.out.println("Unable to start browser");
}
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics