用java编写简单网页浏览器,用到两个类WebBrowser and ViewSourceFreme,他们分别的功能是:
WebBrowser.java 类是网页浏览器的主类文件,生成网页浏览器的主题框架,并实现框架上各个组件的监听事件。ViewSourceFrame.java类是实现网页浏览器源代码查看的主体框架,并提供了源代码的保存功能。
好了,废话少说,直接上代码
package Browser;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.ActionEvent;
import
java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import
java.awt.event.KeyEvent;
import java.io.*;
import
java.util.ArrayList;
import java.net.*;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import
javax.swing.event.HyperlinkListener;
import javax.swing.text.*;
public class WebBrowser extends JFrame implements
HyperlinkListener,
ActionListener {
// 建立工具栏用来显示地址栏
JToolBar bar =
new JToolBar();
// 建立网页显示界面
JTextField jurl = new JTextField(60);
JEditorPane
jEditorPane1 = new JEditorPane();
JScrollPane scrollPane = new
JScrollPane(jEditorPane1);
JFileChooser chooser = new JFileChooser();
JFileChooser chooser1 = new
JFileChooser();
String htmlSource;
JWindow window = new
JWindow(WebBrowser.this);
JButton button2 = new JButton("还原窗口");
Toolkit toolkit =
Toolkit.getDefaultToolkit();
// 建立菜单栏
JMenuBar jMenuBar1 = new JMenuBar();
// 建立菜单组
JMenu
fileMenu = new JMenu("文件(F)");
// 建立菜单项
JMenuItem saveAsItem = new JMenuItem("另存为(A)");
JMenuItem
exitItem = new JMenuItem("退出(X)");
JMenu editMenu = new
JMenu("编辑(E)");
JMenuItem backItem = new JMenuItem("后退");
JMenuItem
forwardItem = new JMenuItem("前进");
JMenu viewMenu = new
JMenu("视图(V)");
JMenuItem fullscreenItem = new
JMenuItem("全屏(U)");
JMenuItem sourceItem = new
JMenuItem("源代码(C)");
JMenuItem reloadItem = new
JMenuItem("刷新(R)");
// 建立工具栏
JToolBar toolBar = new
JToolBar();
// 建立工具栏中的按钮
JButton picSave = new
JButton("另存为");
JButton picBack = new JButton("后退");
JButton picForward
= new JButton("前进");
JButton picView = new JButton("查看源代码");
JButton
picExit = new JButton("退出");
JLabel label = new JLabel("地址");
JButton button = new
JButton("转向");
Box adress =
Box.createHorizontalBox();
//ArrayList对象,用来存放历史地址
private ArrayList
history = new ArrayList();
//整型变量,表示历史地址的访问顺序
private int
historyIndex;
/**
* 构造函数
* 初始化图形用户界面
*/
public
WebBrowser(){
setTitle("网页浏览器");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//为jEditorPane1添加时间侦听
jEditorPane1.addHyperlinkListener(this);
//为组件fileMenu设置热键‘F’
fileMenu.setMnemonic('F');
saveAsItem.setMnemonic('S');
//为“另存为”组件设置快捷键Ctrl+S
saveAsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));
exitItem.setMnemonic('X');
exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,InputEvent.CTRL_MASK));
//将菜单项saveAsItem加入菜单组fileMenu中
fileMenu.add(saveAsItem);
//在菜单项中添加隔离
fileMenu.addSeparator();
fileMenu.add(exitItem);
backItem.setMnemonic('B');
backItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z,InputEvent.CTRL_MASK));
forwardItem.setMnemonic('D');
forwardItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,InputEvent.CTRL_MASK));
editMenu.setMnemonic('E');
editMenu.add(backItem);
editMenu.add(