⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 webbrowser.java

📁 java jdk 实例宝典 源码 夏先波 编著 随书光盘源码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
            
            // 页面打开后,将浏览器窗口的标题设为URL
            this.setTitle(href);  
            // 网址输入框的内容也设置为URL
            urlField.setText(href); 
            return true;
        } catch (IOException ex) { 
        	// 停止动画
            stopAnimation();
            // 状态栏中显示错误信息
            messageLine.setText("不能打开页面:" + ex.getMessage());
            return false;
        }
    }

    /**
     * 浏览器打开URL指定的页面,如果成功,将URL放入历史列表中
     */
    public void displayPage(URL url) {
    	// 尝试访问页面
        if (visit(url)) { 
        	// 如果成功,则将URL放入历史列表中。
            history.add(url); 
            int numentries = history.size();
            if (numentries > MAX_HISTORY+10) { 
                history = history.subList(numentries-MAX_HISTORY, numentries);
                numentries = MAX_HISTORY;
            }
            // 将当前页面下标置为numentries-1
            currentHistoryPage = numentries - 1;
            // 如果当前页面不是第一个页面,则可以后退,允许点击后退按钮。
            if (currentHistoryPage > 0){
            	backButton.setEnabled(true);
            }
        }
    }

    /**
     * 浏览器打开字符串指定的页面
     * @param href	网址
     */
    public void displayPage(String href) {
        try {
        	// 默认为HTTP协议
        	if (!href.startsWith("http://")){
        		href = "http://" + href;
        	}
            displayPage(new URL(href));
        }
        catch (MalformedURLException ex) {
            messageLine.setText("错误的网址: " + href);
        }
    }

    /**
     * 打开本地文件
     */
    public void openLocalPage() {
        // 使用“懒创建”模式,当需要时,才创建文件选择器。
        if (fileChooser == null) {
            fileChooser = new JFileChooser();
            // 使用文件过滤器限制只能够HTML和HTM文件
            FileFilter filter = new FileFilter() {
                    public boolean accept(File f) {
                        String fn = f.getName();
                        if (fn.endsWith(".html") || fn.endsWith(".htm")){
                            return true;
                        }else {
                        	return false;
                        }
                    }
                    public String getDescription() { 
                    	return "HTML Files"; 
                    }
                };
            fileChooser.setFileFilter(filter);
            // 只允许选择HTML和HTM文件
            fileChooser.addChoosableFileFilter(filter);
        }

        // 打开文件选择器
        int result = fileChooser.showOpenDialog(this);
        // 如果确定打开文件,则在当前窗口中打开选择的文件
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile( );
            try {
				displayPage(selectedFile.toURL());
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
        }
    }
    /**
     * 后退,回到前一页
     */
    public void back() {
        if (currentHistoryPage > 0){
        	// 访问前一页
            visit((URL)history.get(--currentHistoryPage));
        }
        // 如果当前页面下标大于0,允许后退
        backButton.setEnabled((currentHistoryPage > 0));
        // 如果当前页面下标不是最后,允许前进
        forwardButton.setEnabled((currentHistoryPage < history.size()-1));
    }
    /**
     * 前进,回到后一页
     */
    public void forward() {
        if (currentHistoryPage < history.size( )-1){
            visit((URL)history.get(++currentHistoryPage));
        }
        // 如果当前页面下标大于0,允许后退
        backButton.setEnabled((currentHistoryPage > 0));
        // 如果当前页面下标不是最后,允许前进
        forwardButton.setEnabled((currentHistoryPage < history.size()-1));
    }
    /**
     * 重新加载当前页面
     */
    public void reload() {
        if (currentHistoryPage != -1) {
            // 先显示为空白页
            textPane.setDocument(new javax.swing.text.html.HTMLDocument());
            // 再访问当前页
            visit((URL)history.get(currentHistoryPage));
        }
    }
    /**
     * 显示主页 
     */
    public void home() {
    	displayPage(getHome()); 
    }
    /**
     * 打开新的浏览器窗口 
     */
    public void newBrowser() {
        WebBrowser b = new WebBrowser();
        // 新窗口大小和当前窗口一样大
        b.setSize(this.getWidth(), this.getHeight());
        b.setVisible(true);
    }
    /**
     * 关闭当前窗口,如果所有窗口都关闭,则根据exitWhenLastWindowClosed属性,
     * 判断是否退出应用程序
     */
    public void close() {
    	// 先隐藏当前窗口,销毁窗口中的组件。
        this.setVisible(false);
        this.dispose();
        // 将当前打开窗口数减1。
        // 如果所有窗口都已关闭,而且exitWhenLastWindowClosed为真,则退出
        // 这里采用了synchronized关键字,保证线程安全
        synchronized(WebBrowser.class) {    
            WebBrowser.numBrowserWindows--; 
            if ((numBrowserWindows==0) && exitWhenLastWindowClosed){
                System.exit(0);
            }
        }
    }
    /**
     * 退出应用程序
     */
    public void exit() {
    	// 弹出对话框,请求确认,如果确认退出,则退出应用程序
		if ((JOptionPane.showConfirmDialog(this, "你确定退出Web浏览器?", "退出",
				JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)){
			System.exit(0);
		}
	}
    /**
     * 实现HyperlinkListener接口。处理超连接事件
     */
    public void hyperlinkUpdate(HyperlinkEvent e) {
    	// 获取事件类型
        HyperlinkEvent.EventType type = e.getEventType();
        // 如果是点击了一个超连接,则显示被点击的连接
        if (type == HyperlinkEvent.EventType.ACTIVATED) {
            displayPage(e.getURL());
        }
        // 如果是鼠标移动到超连接上,则在状态栏中显示超连接的网址
        else if (type == HyperlinkEvent.EventType.ENTERED) {
            messageLine.setText(e.getURL().toString());  
        }
        // 如果是鼠标离开了超连接,则状态栏显示为空
        else if (type == HyperlinkEvent.EventType.EXITED) { 
            messageLine.setText(" ");
        }
    }

    /**
     * 实现PropertyChangeListener接口。处理属性改变事件。
     * 显示HTML面板textPane的属性改变时,由该方法处理。
     * 当textPane调用完setPage方法时,page属性便改变了。
     */
    public void propertyChange(PropertyChangeEvent e) {
        if (e.getPropertyName().equals("page")) {
        	// 页面加载完毕时,textPane的page属性发生改变,此时停止动画。
            stopAnimation();
        }
    }

    // 动画消息,显示在最底下状态栏标签上,用于反馈浏览器的状态
    String animationMessage;
    // 动画当前的帧的索引
    int animationFrame = 0;
    // 动画所用到的帧,是一些字符。
    String[] animationFrames = new String[] {
        "-", "\\", "|", "/", "-", "\\", "|", "/", 
        ",", ".", "o", "0", "O", "#", "*", "+"
    };

    /**
     * 新建一个Swing的定时器,每个125毫秒更新一次状态栏标签的文本
     */
    javax.swing.Timer animator =
        new javax.swing.Timer(125, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                	animate(); 
                }
            });

    /**
     * 显示动画的当前帧到状态栏标签上,并将帧索引后移
     */
    private void animate() {
        String frame = animationFrames[animationFrame++];
        messageLine.setText(animationMessage + " " + frame);
        animationFrame = animationFrame % animationFrames.length;
    }

    /**
     * 启动动画
     */
    private void startAnimation(String msg) {
        animationMessage = msg;
        animationFrame = 0; 
        // 启动定时器
        animator.start();
    }

    /**
     * 停止动画
     */
    private void stopAnimation() {  
    	// 停止定时器
        animator.stop();
        messageLine.setText(" ");
    }
    
    public static void main(String[] args) throws IOException {
        // 设置浏览器,当所有浏览器窗口都被关闭时,退出应用程序
		WebBrowser.setExitWhenLastWindowClosed(true);
		// 创建一个浏览器窗口
		WebBrowser browser = new WebBrowser(); 
		// 设置浏览器窗口的默认大小
		browser.setSize(800, 600);
		// 显示窗口
        browser.setVisible(true); 

        // 打开主页
        browser.displayPage(browser.getHome());
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -