使用jswing自制簡單瀏覽器 實現瀏覽網絡及本地資源 有前進,后退,刷新,文件新建等功能

jopen 10年前發布 | 27K 次閱讀 jswing Swing Java開發

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;

import javax.swing.JButton; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.filechooser.FileFilter; /**

    fileMenu.add(newMenuItem);                      //將新建項添加到文件菜單下 
    fileMenu.add(openMenuItem);                     //將打開項添加到文件菜單下
    fileMenu.add(closeMenuItem);                    //將關閉項添加到文件菜單下

    JMenuBar menuBar=new JMenuBar();                //創建菜單欄
    menuBar.add(fileMenu);                          //將文件菜單放入到菜單欄
    this.setJMenuBar(menuBar);                      //設置菜單欄到主窗口上


}

//初始化從工具欄
private void initToolbar() {
    // TODO Auto-generated method stub
    back=new JButton("后退");                         //創建后退按鈕
    back.setEnabled(false);                         //不可用
    //設置后退事件
    back.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            back();                     //調用后退方法
        }
    });

    forward=new JButton("前進");                      //創建前進按鈕
    forward.setEnabled(false);                      //不可用
    //設置前進事件
    forward.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            forward();                  //調用前進方法
        }
    });

    JButton refreshButton=new JButton("刷新");
    //refreshButton.setMnemonic('F5');
    //刷新觸發事件
    refreshButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            reload();               //調用重新加載方法
        }
    });


    JToolBar toolBar=new JToolBar();
    toolBar.add(back);
    toolBar.add(forward);
    toolBar.add(refreshButton);

    url=new JTextField();                       //創建文本框
    //輸入地址欄 回車事件
    url.addActionListener(new  ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            displayPage(url.getText()); //
        }
    });

    toolBar.add(new JLabel("\t\t地址:"));  //添加地址標簽
    toolBar.add(url);

    this.getContentPane().add(toolBar,BorderLayout.NORTH);


}
private static void closeWindowWhenAllExit(boolean b) {
    // TODO Auto-generated method stub
    exit=b;
}
//設置主頁
public String getHome() {
    return home;
}

public void setHome(String home) {
    this.home = home;
}

//訪問網址URL
private boolean visitURL(URL source){
    try {
        System.out.println(source.toString());
        String href=source.toString();          //獲取網址
        Pane.setPage(source);                   //設置待訪問的URL
        this.setTitle(href);                    //頁面打開后 將瀏覽器的窗口的標題設置為URL
        url.setText(href);                      //網址輸入框的內容也設置為URL
        return true;
    } catch (Exception e) {
        messageLine.setText("不能打開頁面:"+e.getMessage());
        return false;
    }
}

//打開URL指定的頁面,URL放入歷史列表中
public void displayPage(URL url) {
    // TODO Auto-generated method stub
    if(visitURL(url)){                              //訪問頁面是否成功
        historyReport.add(url);                     //URL放入歷史表中
        int numentries=historyReport.size();
        if(numentries > maxHistory+10){
            historyReport=historyReport.subList(numentries-maxHistory, numentries);
            numentries=maxHistory;
        }
        current=numentries-1;
        if(current>0){                               //不是當前頁面
            back.setEnabled(true);                  // 運行使用后退按鈕
        }
    }
}
//瀏覽器打開指定頁面
public void displayPage(String href) {
    try {
        if(!href.startsWith("http://")){            //默認為HTTP協議
            href="http://"+href;
        }
        displayPage(new URL(href));
    } catch (Exception e) {
        messageLine.setText("錯誤網址:"+href);
    }

}

//打開本地文件
protected void openLocalPage() {
    // TODO Auto-generated method stub
    if(fileChooser==null){
        fileChooser=new JFileChooser();             //創建文件選擇器
        FileFilter filter=new  FileFilter(){        //文件過濾器 限制只接受 HTML和 HTM文件

            @Override
            public boolean accept(File pathname) {
                String fn=pathname.getName();
                if(fn.endsWith(".html") || fn.endsWith(".htm")){
                    return true;
                }else {
                    return false;
                }
            }

            @Override
            public String getDescription() {
                // TODO Auto-generated method stub
                return "HEML Files";
            }
        };

        fileChooser.setFileFilter(filter);
        fileChooser.addChoosableFileFilter(filter);
    }

    int result=fileChooser.showOpenDialog(this);            //打開文件選擇器 模式窗體

    if(result==JFileChooser.APPROVE_OPTION){                //選擇確定按鈕
        File selectedFile=fileChooser.getSelectedFile();
        try {
            displayPage(selectedFile.toURL());                              
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

//后退的方法
protected void back() {
    // TODO Auto-generated method stub
    if(current>0){
        visitURL((URL)historyReport.get(--current));    //訪問前一頁面
    }           
    back.setEnabled((current>0));                        //當前下標>0 才可后退
    forward.setEnabled((current<historyReport.size()-1));
}
//前進的方法
protected void forward() {
    // TODO Auto-generated method stub
    if(current<historyReport.size()-1){
        visitURL((URL)historyReport.get(current++));    //訪問后一個頁面
    }
    back.setEnabled((current>0));
    forward.setEnabled((current<historyReport.size()-1));
}

//重新加載頁面
protected void reload() {
    // TODO Auto-generated method stub
    if(current!=-1){  //顯示空白頁面
        Pane.setDocument(new javax.swing.text.html.HTMLDocument());
        visitURL((URL)historyReport.get(current));      //訪問當前頁面
    }
}
//顯示主頁方法
public void home(){
    displayPage(getHome());
}
//關閉
protected void close() {
    // TODO Auto-generated method stub
    this.setVisible(false); //隱藏當前窗口,銷毀窗口中的一些組件
    this.dispose();
    synchronized (TextWebBrowser.class) {
        TextWebBrowser.count--;
        if((count==0) && exit){
            System.exit(0);
        }
    }
}

//退出
protected void exit() {
    // TODO Auto-generated method stub
    if(JOptionPane.showConfirmDialog(this, "你確定退出web瀏覽器?","退出",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){ //判斷是否退出
        System.exit(0);
    }
}
//打開新的瀏覽器窗口
protected void newBrower() {
    // TODO Auto-generated method stub
    TextWebBrowser b=new TextWebBrowser();
    b.setSize(this.getWidth(),this.getHeight());        //窗口與當前窗口一樣大
    b.setVisible(true);

}
//處理超鏈接的事件
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
    // TODO Auto-generated method stub
    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(" ");
    }
}

public static void main(String[]args){
    TextWebBrowser.closeWindowWhenAllExit(true);
    TextWebBrowser brower=new TextWebBrowser();
    brower.setSize(500,400);
    brower.setVisible(true); //顯示窗口
    brower.displayPage(brower.getHome());
}



}</pre>轉載自:http://takeme.iteye.com/blog/1828332

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!