天天看點

教你三分鐘制作浏覽器

父類,定義一個架構

import javax.swing.JFrame;

public class subJFrame extends JFrame{

 private static final long serialVersionUID = 1L;

 public subJFrame(){}

 public subJFrame(String title){

  super(title);

 }

 protected void frameInit(){

  super.frameInit();

  setDefaultCloseOperation(EXIT_ON_CLOSE);

 }

}

浏覽器主類開始:

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.net.*;

import javax.swing.*;

import javax.swing.event.*;

@SuppressWarnings("unused")

public class browseWeb extends subJFrame{

 private static final long serialVersionUID = 1L;

 private JTextField enterField;

 private JEditorPane contentsArea;

 @SuppressWarnings("deprecation")

 public browseWeb(){

  super("Web browser");

  enterField = new JTextField( "請在此輸入網址" );   

        enterField.addActionListener(  

            new ActionListener( ) {           

                public void actionPerformed( ActionEvent event ){

                    getThePage( event.getActionCommand( ) ); 

                }

             }

        );

  Container container=getContentPane();

  container.add(enterField,BorderLayout.NORTH);

  contentsArea=new JEditorPane();

  contentsArea.setEditable(false);

  contentsArea.addHyperlinkListener(

    new HyperlinkListener(){

    public void hyperlinkUpdate(HyperlinkEvent event){

     if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED)

      getThePage(event.getURL().toString());

    }

    });

  container.add(new JScrollPane(contentsArea),BorderLayout.CENTER);

  setSize(500,250);

  show();

 }

 private void getThePage(String location){

  setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

  try{

   contentsArea.setPage(location);

   enterField.setText(location);

  }catch(IOException ioException){

   JOptionPane.showMessageDialog(this,"網址錯誤",

     "網址出錯",JOptionPane.ERROR_MESSAGE); 

  }

  setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

 }

 public static void main(String[] args) {

  browseWeb application=new browseWeb();

 }

}

生成jar檔案輕按兩下即可運作,呵呵

效果:

教你三分鐘制作浏覽器

繼續閱讀