1 package com.yw.ie;
2
3 import java.awt.*;
4 import java.io.IOException;
5 import java.net.URL;
6 import javax.swing.*;
7 import java.awt.event.*;
8 import javax.swing.event.*;
9
10 public class WebBrowser extends JFrame{
11
12 JPanel contentPane;
13 BorderLayout borderLayoutAll=new BorderLayout();
14 JLabel jLabelPrompt=new JLabel(); //状态提示框
15 BorderLayout borderLayoutMain=new BorderLayout();
16 JPanel jPanelMain=new JPanel();
17 JTextField textFieldURL=new JTextField(); //URL输入框
18 JEditorPane jEditorPane=new JEditorPane(); //显示网页容器
19
20 /**
21 * 构造函数
22 * @param args
23 */
24 public WebBrowser(){
25
26 try {
27 Init();
28 } catch (Exception e) {
29 // TODO 自动生成 catch 块
30 e.printStackTrace();
31 }
32
33 }
34 private void Init() throws Exception{
35 contentPane=(JPanel) getContentPane();
36 contentPane.setLayout(borderLayoutAll);
37 jPanelMain.setLayout(borderLayoutMain);
38 jLabelPrompt.setText("请输入URL");
39 textFieldURL.setText("");
40 textFieldURL.addActionListener(new java.awt.event.ActionListener(){
41 public void actionPerformed(ActionEvent e){
42 textFieldURL_actionPerformed(e);
43 }
44 });
45 jEditorPane.setEditable(false);
46 jEditorPane.addHyperlinkListener(new javax.swing.event.HyperlinkListener(){
47 public void hyperlinkUpdate(HyperlinkEvent e){
48 jEditorPane_hyperlinkUpdate(e);
49 }
50 });
51 JScrollPane scrollPane=new JScrollPane();
52 scrollPane.getViewport().add(jEditorPane);
53 jPanelMain.add(textFieldURL,"North");
54 jPanelMain.add(scrollPane,"Center");
55 contentPane.add(jLabelPrompt,"North");
56 contentPane.add(jPanelMain,"Center");
57 enableEvents(AWTEvent.WINDOW_EVENT_MASK);
58 this.setSize(new Dimension(600,500));
59 this.setTitle("迷你IE");
60 this.setVisible(true);
61 }
62 void textFieldURL_actionPerformed(ActionEvent e){
63 try {
64 jEditorPane.setPage(textFieldURL.getText());//显示URL
65 } catch (IOException e1) {
66 JOptionPane msg=new JOptionPane();
67 JOptionPane.showMessageDialog(this, "URL地址不正确:"+textFieldURL.getText(),"输入不正确",0);
68 }
69
70 }
71 void jEditorPane_hyperlinkUpdate(HyperlinkEvent e){
72 if(e.getEventType()==javax.swing.event.HyperlinkEvent.EventType.ACTIVATED){
73 try {
74 URL url=e.getURL();
75 jEditorPane.setPage(url);
76 textFieldURL.setText(url.toString());
77 } catch (Exception io) {
78 // TODO: handle exception
79 JOptionPane msg=new JOptionPane();
80 JOptionPane.showMessageDialog(this,"打开该链接失败!","输入不正确",0);
81 }
82
83 }
84 }
85 protected void processWindowEvent (WindowEvent e){
86 super.processWindowEvent(e);
87 if(e.getID()==WindowEvent.WINDOW_CLOSING){
88 System.exit(0);
89 }
90 }
91 public static void main(String[] args) {
92
93 new WebBrowser();
94 }
95
96 }