chenmin200396
发贴: 1
积分: 0
|
于 2006-07-30 22:02
package HtmlBrowser;
import java.io.IOException; import java.net.URL; import javax.swing.*; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import java.awt.*; import java.awt.event.*; import javax.swing.event.*;
public class HtmlBrowser extends JFrame { JPanel contentPane; // 包含整个框架的容器 BorderLayout borderLayoutAll = new BorderLayout(); JLabel jLabelPrompt = new JLabel(); // 状态提示框 JPanel jPanelMain = new JPanel(); // 包含URL编辑框和JEditorPane的容器 BorderLayout borderLayoutMain = new BorderLayout(); JTextField textFieldURL = new JTextField(); // URL输入框 JEditorPane jEditorPane = new JEditorPane(); // 显示网页内容的容器
// 构造函数 public HtmlBrowser() { try { jbInit(); // 初始化并显示界面 } catch(Exception e) { e.printStackTrace(); } }
// 初始化并显示界面 private void jbInit() throws Exception { contentPane = (JPanel)getContentPane(); contentPane.setLayout(borderLayoutAll);
jPanelMain.setLayout(borderLayoutMain); jLabelPrompt.setText("请输入完整的URL"); textFieldURL.setText(""); textFieldURL.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { textFieldURL_actionPerformed; } }); jEditorPane.setEditable(false); jEditorPane.addHyperlinkListener(new javax.swing.event.HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { jEditorPane_hyperlinkUpdate; } }); JScrollPane scrollPane = new JScrollPane(); scrollPane.getViewport().add(jEditorPane); jPanelMain.add(textFieldURL, "North"); jPanelMain.add(scrollPane, "Center"); contentPane.add(jLabelPrompt, "North"); contentPane.add(jPanelMain, "Center"); enableEvents(AWTEvent.WINDOW_EVENT_MASK); this.setSize(new Dimension(800, 600)); this.setTitle("网页浏览器"); this.setVisible(true); }
// 响应回车 void textFieldURL_actionPerformed(ActionEvent e) { try { jEditorPane.setPage(textFieldURL.getText()); // 显示所给的URL内容 } catch(IOException ex) { JOptionPane msg = new JOptionPane(); // 提示对话框 JOptionPane.showMessageDialog(this, "不正确的URL地址:"+textFieldURL.getText(), "不正确的输入!", 0); } }
// 响应打开超级链接的消息 void jEditorPane_hyperlinkUpdate(HyperlinkEvent e) { if(e.getEventType() == javax.swing.event.HyperlinkEvent.EventType.ACTIVATED) { try { URL url = e.getURL(); // 从消息中得到URL地址 jEditorPane.setPage(url); // 显示该URL页面的内容 textFieldURL.setText(url.toString()); // 显示URL地址 } catch(IOException io){ JOptionPane msg = new JOptionPane(); JOptionPane.showMessageDialog(this, "无法打开链接!", "输入错误!", 0); } } }
// 关闭窗口 protected void processWindowEvent(WindowEvent e) { super.processWindowEvent; if (e.getID() == WindowEvent.WINDOW_CLOSING) { System.exit(0); } } // 主函数 public static void main(String[] args) { new HtmlBrowser(); } }
|