import?java.awt.*;?
目前成都創(chuàng)新互聯(lián)已為上千余家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)絡(luò)空間、網(wǎng)站托管、服務(wù)器租用、企業(yè)網(wǎng)站設(shè)計、潞州網(wǎng)站維護(hù)等服務(wù),公司將堅持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。
import?java.awt.event.*;?
import?java.io.IOException;?
import?java.net.*;?
import?javax.swing.*;?
import?javax.swing.event.HyperlinkEvent;?
import?javax.swing.event.HyperlinkListener;?
public?class?HTTPBrowserDemo?extends?JFrame?{?
private?JLabel?jlAddress,jlInfo;?
private?JTextField?jtfAddress;?
private?JEditorPane?jtpShow;?
private?JPanel?panel;?
private?JButton?btnGO;?
public?static?void?main(String[]?args)?{?
HTTPBrowserDemo?hbd=new?HTTPBrowserDemo();?
}?
HTTPBrowserDemo(){?
jlAddress=new?JLabel("地址");?
jlInfo=new?JLabel();?
jtpShow=new?JEditorPane();?
panel=new?JPanel();?
jtfAddress=new?JTextField(20);?
btnGO=new?JButton("轉(zhuǎn)到");?
add(panel,BorderLayout.NORTH);?
add(jtpShow,BorderLayout.CENTER);?
add(jlInfo,BorderLayout.SOUTH);?
panel.add(jlAddress);?
panel.add(jtfAddress);?
panel.add(btnGO);?
setVisible(true);?
setSize(350,?280);?
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);?
btnGO.addActionListener(new?ShowHTMLListener());?
jtpShow.setEditable(false);?
jtpShow.addHyperlinkListener(new?MyHyperlinkListener());?
}?
class?ShowHTMLListener?implements?ActionListener{?
public?void?actionPerformed(ActionEvent?e){?
String?str=jtfAddress.getText();?
try?{?
if?(!str.startsWith("http://")){?
str="http://"+str;?
}?
jlInfo.setText("連接中...");?
URL?address=new?URL(str);?
jtpShow.setPage(address);?
jlInfo.setText("完成");?
}?catch?(MalformedURLException?e1)?{?
//?TODO?Auto-generated?catch?block?
e1.printStackTrace();?
}?catch?(IOException?e2)?{?
//?TODO:?handle?exception?
}?
}?
}?
class?MyHyperlinkListener?implements?HyperlinkListener{?
public?void?hyperlinkUpdate(HyperlinkEvent?e)?{?
if(e.getEventType()==HyperlinkEvent.EventType.ACTIVATED){?
JEditorPane?pane=(JEditorPane)e.getSource();?
try?{?
pane.setPage(e.getURL());?
}?catch?(IOException?e1)?{?
//?TODO?Auto-generated?catch?block?
e1.printStackTrace();?
}?
}?
}?????????
}?
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.event.*;
@SuppressWarnings("serial")
class Win3 extends JFrame implements ActionListener,Runnable
{
JButton button;
URL url;
JTextField text;
JEditorPane editPane;
byte b[]=new byte[118];
Thread thread;
public Win3()
{
text=new JTextField(20);
editPane=new JEditorPane();
editPane.setEditable(false);
button=new JButton("確定");
button.addActionListener(this);
thread=new Thread(this);
JPanel p=new JPanel();
p.add(new JLabel("輸入網(wǎng)址:"));
p.add(text);
p.add(button);
Container con=getContentPane();
con.add(new JScrollPane(editPane),BorderLayout.CENTER);
con.add(p,BorderLayout.NORTH);
setBounds(60,60,400,300);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editPane.addHyperlinkListener(new HyperlinkListener()
{
public void hyperlinkUpdate(HyperlinkEvent e)
{
if(e.getEventType()==
HyperlinkEvent.EventType.ACTIVATED)
{
try{
editPane.setPage(e.getURL());
}
catch(IOException e1)
{
editPane.setText(""+e1);
}
}
}
}
);
}
public void actionPerformed(ActionEvent e)
{
if(!(thread.isAlive()))
thread=new Thread(this);
try{
thread.start();
}
catch(Exception ee)
{
text.setText("我正在讀取"+url);
}
}
public void run()
{
try {
int n=-1;
editPane.setText(null);
url=new URL(text.getText().trim());
editPane.setPage(url);
}
catch(MalformedURLException e1)
{
text.setText(""+e1);
return;
}
catch(IOException e1)
{
text.setText(""+e1);
return;
}
}
}
public class Example3
{
public static void main(String args[])
{
new Win3();
}
}
html
head
script
function move(){
var x = Math.floor(Math.random()*800);
var y = Math.floor(Math.random()*600);
var r = Math.floor(Math.random()*16).toString(16);
var g = Math.floor(Math.random()*16).toString(16);
var b = Math.floor(Math.random()*16).toString(16);
document.getElementById("prank1").style.marginLeft = x+"px";
document.getElementById("prank1").style.marginTop = y+"px";
x = Math.floor(Math.random()*800);
y = Math.floor(Math.random()*600);
r = Math.floor(Math.random()*16).toString(16);
g = Math.floor(Math.random()*16).toString(16);
b = Math.floor(Math.random()*16).toString(16);
document.getElementById("prank2").style.marginLeft = x+"px";
document.getElementById("prank2").style.marginTop = y+"px";
document.body.style.background ="#"+r+g+b;
}
function win(){
alert("You Win!!!");
}
/script
/head
body
button id="close" onclick="window.close()"close window/button
button id="prank1" onMouseMove="move()" onClick="win()"Click Me/button
button id="prank2" onMouseMove="move()" onClick="win()"Click Me/button
/body
/html
3.WebBrowser.java
package CH04.源程序;
/*
**網(wǎng)頁瀏覽器主程序
**WebBrowser.java
*/
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileView;
import java.io.*;
import java.net.*;
import java.util.*;
public class WebBrowser extends JFrame implements HyperlinkListener,ActionListener{
//建立工具欄用來顯示地址欄
JToolBar bar=new JToolBar ();
//建立網(wǎng)頁顯示界面
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 ("退出(I)");
JMenu editMenu=new JMenu ("編輯(E)");
JMenuItem backItem=new JMenuItem ("后退");
JMenuItem forwardItem=new JMenuItem ("前進(jìn)");
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("前進(jìn)");
JButton picView = new JButton("查看源代碼");
JButton picExit = new JButton("退出");
JLabel label=new JLabel ("地址");
JButton button=new JButton ("轉(zhuǎn)向");
Box adress=Box.createHorizontalBox ();
//ArrayList對象,用來存放歷史地址
private ArrayList history=new ArrayList();
//整型變量,表示歷史地址的訪問順序
private int historyIndex;
/**
**構(gòu)造函數(shù)
**初始化圖形用戶界面
*/
public WebBrowser(){
setTitle ("網(wǎng)頁瀏覽器");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//為jEditorPane1添加事件偵聽
jEditorPane1.addHyperlinkListener (this);
//為組件fileMenu設(shè)置熱鍵‘F’
fileMenu.setMnemonic('F');
saveAsItem.setMnemonic ('S');
//為“另存為”組件設(shè)置快捷鍵為ctrl+s
saveAsItem.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_S,InputEvent.CTRL_MASK));
exitItem.setMnemonic('Q');
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 (forwardItem);
viewMenu.setMnemonic('V');
fullscreenItem.setMnemonic('U');
fullscreenItem.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_U,InputEvent.CTRL_MASK));
sourceItem.setMnemonic('C');
sourceItem.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_C,InputEvent.CTRL_MASK));
reloadItem.setMnemonic('R');
reloadItem.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_R,InputEvent.CTRL_MASK));
Container contentPane=getContentPane ();
//設(shè)置大小
scrollPane.setPreferredSize(new Dimension(100,500));
contentPane.add (scrollPane, BorderLayout.SOUTH);
//在工具欄中添加按鈕組件
toolBar.add(picSave);
toolBar.addSeparator();
toolBar.add(picBack);
toolBar.add(picForward);
toolBar.addSeparator();
toolBar.add(picView);
toolBar.addSeparator();
toolBar.add(picExit);
contentPane.add (bar,BorderLayout.CENTER);
contentPane.add(toolBar,BorderLayout.NORTH);
viewMenu.add (fullscreenItem);
viewMenu.add (sourceItem);
viewMenu.addSeparator ();
viewMenu.add (reloadItem);
jMenuBar1.add (fileMenu);
jMenuBar1.add (editMenu);
jMenuBar1.add (viewMenu);
setJMenuBar (jMenuBar1);
adress.add (label);
adress.add (jurl);
adress.add (button);
bar.add (adress);
//為組件添加事件監(jiān)聽
saveAsItem.addActionListener(this);
picSave.addActionListener(this);
exitItem.addActionListener(this);
picExit.addActionListener(this);
backItem.addActionListener(this);
picBack.addActionListener(this);
forwardItem.addActionListener(this);
picForward.addActionListener(this);
fullscreenItem.addActionListener(this);
sourceItem.addActionListener(this);
picView.addActionListener(this);
reloadItem.addActionListener(this);
button.addActionListener(this);
jurl.addActionListener(this);
}
/**
**實現(xiàn)監(jiān)聽器接口的actionPerformed函數(shù)
*/
public void actionPerformed(ActionEvent e) {
String url = "";
//點擊轉(zhuǎn)向按鈕
if (e.getSource() == button){
//獲得地址欄的內(nèi)容
url=jurl.getText ();
//url不為“”,并且以“http://”開頭
if(url.length ()0url.startsWith ("http://")){
try {
//JEditorPane組件顯示url的內(nèi)容鏈接
jEditorPane1.setPage (url);
//將url的內(nèi)容添加到ArrayList對象history中
history.add(url);
//historyIndex的數(shù)值設(shè)為history對象的長度-1
historyIndex=history.size()-1;
//重新布局
jEditorPane1.setEditable(false); //add by copy editor :)
jEditorPane1.revalidate ();
}
catch(Exception ex) {
//如果鏈接顯示失敗,則彈出選擇對話框“無法打開該搜索頁”
JOptionPane.showMessageDialog (WebBrowser.this,"無法打開該搜索頁","網(wǎng)頁瀏覽器",JOptionPane.ERROR_MESSAGE);
}
}
//url不為“”,并且不以“http://”開頭
else if(url.length ()0!url.startsWith ("http://")) {
//在url前面添加“http://”
url="http://"+url;
try {
jEditorPane1.setPage (url );
history.add(url);
historyIndex=history.size()-1;
jEditorPane1.setEditable(false); //add by copy editor :)
jEditorPane1.revalidate ();
}
catch(Exception ex) {
JOptionPane.showMessageDialog (WebBrowser.this,"無法打開該搜索頁","網(wǎng)頁瀏覽器",JOptionPane.ERROR_MESSAGE);
}
}
//沒有輸入url,即url為空
else if(url.length ()==0){
JOptionPane.showMessageDialog (WebBrowser.this,"請輸入鏈接地址","網(wǎng)頁瀏覽器",JOptionPane.ERROR_MESSAGE);
}
}
//輸入地址后點擊回車
else if (e.getSource() == jurl){
url=jurl.getText ();
if(url.length ()0url.startsWith ("http://")) {
try {
jEditorPane1.setPage (url);
history.add(url);
historyIndex=history.size()-1;
jEditorPane1.setEditable(false); //add by copy editor :)
jEditorPane1.revalidate ();
jurl.setMaximumSize (jurl.getPreferredSize ());
}
catch(Exception ex) {
JOptionPane.showMessageDialog (WebBrowser.this,"無法打開該搜索頁","網(wǎng)頁瀏覽器",JOptionPane.ERROR_MESSAGE);
}
}
else if(url.length ()0!url.startsWith ("http://")) {
url="http://"+url;
try {
jEditorPane1.setPage (url );
history.add(url);
historyIndex=history.size()-1;
jEditorPane1.setEditable(false); //add by copy editor :)
jEditorPane1.revalidate ();
}
catch(Exception ex) {
JOptionPane.showMessageDialog (WebBrowser.this,"無法打開該搜索頁","網(wǎng)頁瀏覽器",JOptionPane.ERROR_MESSAGE);
}
}
else if(url.length ()==0){
JOptionPane.showMessageDialog (WebBrowser.this,"請輸入鏈接地址","網(wǎng)頁瀏覽器",JOptionPane.ERROR_MESSAGE);
}
}
//另存為...
else if (e.getSource() == picSave||e.getSource() == saveAsItem){
url = jurl.getText ().toString ().trim();
if(url.length ()0!url.startsWith ("http://")) {
url="http://"+url;
}
if(!url.equals ("")) {
//保存文件
saveFile(url);
}
else {
JOptionPane.showMessageDialog (WebBrowser.this,"請輸入鏈接地址","網(wǎng)頁瀏覽器",JOptionPane.ERROR_MESSAGE);
}
}
//退出
else if (e.getSource() == exitItem ||e.getSource() == picExit){
System.exit(0);
}
//后退
else if (e.getSource() == backItem ||e.getSource() == picBack){
historyIndex--;
if(historyIndex 0)
historyIndex = 0;
url = jurl.getText();
try{
//獲得history對象中本地址之前訪問的地址
url = (String)history.get(historyIndex);
jEditorPane1.setPage(url);
jurl.setText(url.toString());
jEditorPane1.setEditable(false); //add by copy editor :)
jEditorPane1.revalidate ();
}
catch(Exception ex){
}
}
//前進(jìn)
else if (e.getSource() == forwardItem ||e.getSource() == picForward){
historyIndex++;
if(historyIndex = history.size())
historyIndex = history.size()-1;
url = jurl.getText();
try{
//獲得history對象中本地址之后訪問的地址
url = (String)history.get(historyIndex);
jEditorPane1.setPage(url);
jurl.setText(url.toString());
jEditorPane1.setEditable(false); //add by copy editor :)
jEditorPane1.revalidate ();
}
catch(Exception ex){
}
}
//全屏
else if (e.getSource() == fullscreenItem){
boolean add_button2=true;
//獲得屏幕大小
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
Container content = window.getContentPane();
content.add (bar,"North");
content.add (scrollPane,"Center");
//button2為點擊“全屏”后的還原按鈕
if(add_button2==true) {
bar.add (button2);
}
//為button2添加事件
button2.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent evt) {
WebBrowser.this.setEnabled (true);
window.remove (bar);
window.remove (toolBar);
window.remove (scrollPane);
window.setVisible (false);
scrollPane.setPreferredSize (new Dimension (100,500));
getContentPane ().add (scrollPane,BorderLayout.SOUTH);
getContentPane ().add (bar,BorderLayout.CENTER);
getContentPane ().add (toolBar,BorderLayout.NORTH);
bar.remove (button2);
pack();
}
});
window.setSize (size);
window.setVisible (true);
}
//查看源文件
else if (e.getSource() == sourceItem ||e.getSource() == picView){
url = jurl.getText ().toString ().trim ();
if(url.length ()0!url.startsWith ("http://")) {
url="http://"+url;
}
if( !url.equals ("")) {
//根據(jù)url,獲得源代碼
getHtmlSource (url);
//生成顯示源代碼的框架對象
ViewSourceFrame vsframe = new ViewSourceFrame (htmlSource);
vsframe.setBounds (0,0,800,500);
vsframe.setVisible(true);
}
else {
JOptionPane.showMessageDialog (WebBrowser.this,"請輸入鏈接地址","網(wǎng)頁瀏覽器",JOptionPane.ERROR_MESSAGE);
}
}
//刷新
else if (e.getSource() == reloadItem){
url=jurl.getText ();
if(url.length ()0url.startsWith ("http://")) {
try {
jEditorPane1.setPage (url);
jEditorPane1.setEditable(false); //add by copy editor :)
jEditorPane1.revalidate ();
}
catch(Exception ex) {
}
}
else if(url.length ()0!url.startsWith ("http://")) {
url="http://"+url;
try {
jEditorPane1.setPage (url );
jEditorPane1.setEditable(false); //add by copy editor :)
jEditorPane1.revalidate ();
}
catch(Exception ex) {
}
}
}
}
/*
**保存文件
*/
void saveFile (final String url) {
final String linesep = System.getProperty ("line.separator");
chooser1.setCurrentDirectory (new File ("."));
chooser1.setDialogType (JFileChooser.SAVE_DIALOG);
chooser1.setDialogTitle ("另存為...");
if(chooser1.showSaveDialog (this) != JFileChooser.APPROVE_OPTION)
return;
this.repaint ();
Thread thread = new Thread () {
public void run () {
try {
java.net.URL source = new URL (url);
InputStream in = new BufferedInputStream (source.openStream ());
BufferedReader br=new BufferedReader (new InputStreamReader (in));
File fileName = chooser1.getSelectedFile ();
FileWriter out = new FileWriter (fileName);
BufferedWriter bw = new BufferedWriter (out);
String line;
while((line = br.readLine ()) != null) {
bw.write (line);
bw.newLine ();
}
bw.flush ();
bw.close ();
out.close ();
String dMessage = url + " 已經(jīng)被保存至"+ linesep +fileName.getAbsolutePath ();
String dTitle = "另存為";
int dType = JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog ((Component) null,dMessage,dTitle,dType);
}
catch(java.net.MalformedURLException muex) {
JOptionPane.showMessageDialog ((Component)null,muex.toString (),"網(wǎng)頁瀏覽器",JOptionPane.ERROR_MESSAGE);
}
catch(Exception ex) {
JOptionPane.showMessageDialog ((Component) null,ex.toString (),"網(wǎng)頁瀏覽器",JOptionPane.ERROR_MESSAGE);
}
}
};
thread.start ();
}
/*
**獲得源代碼
*/
void getHtmlSource (String url) {
String linesep,htmlLine;
linesep = System.getProperty ("line.separator");
htmlSource ="";
try {
java.net.URL source = new URL (url);
InputStream in = new BufferedInputStream (source.openStream ());
BufferedReader br = new BufferedReader ( new InputStreamReader (in));
while((htmlLine = br.readLine ())!=null) {
htmlSource = htmlSource +htmlLine+linesep;
}
}
catch(java.net.MalformedURLException muex) {
JOptionPane.showMessageDialog (WebBrowser.this,muex.toString (),"網(wǎng)頁瀏覽器",JOptionPane.ERROR_MESSAGE);
}
catch(Exception e) {
JOptionPane.showMessageDialog (WebBrowser.this,e.toString (),"網(wǎng)頁瀏覽器",JOptionPane.ERROR_MESSAGE);
}
}
/**
**實現(xiàn)監(jiān)聽器接口的hyperlinkUpdate函數(shù)
*/
public void hyperlinkUpdate (HyperlinkEvent e) {
/* if(e.getEventType () == HyperlinkEvent.EventType.ACTIVATED) {
String url = jurl.getText();
if(url.length ()0url.startsWith ("http://")) {
try {
jEditorPane1.setPage (url);
jEditorPane1.revalidate ();
}
catch(Exception ex) {
}
}
else if(url.length ()0!url.startsWith ("http://")) {
url="http://"+url;
try {
jEditorPane1.setPage (url );
jEditorPane1.revalidate ();
}
catch(Exception ex) {
}
}
}
*/
// Revised by copy editor :) Now with new code to help hyperlink
try {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
jEditorPane1.setPage(e.getURL());
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
}
/*生成一個IE對象*/
public static void main (String [] args){
try{
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName()
);
}
catch(Exception e){
}
WebBrowser webBrowser = new WebBrowser ();
webBrowser.pack();
webBrowser.setVisible(true);
}
}
Scanner input = new Scanner(System.in);
System.out.print("請輸入一段字符:");
String s = input.next();
System.out.println("請輸入要查詢的字符串:");
String a = input.next();
int index = s.indexOf(a);
List ls = new ArrayList();
while (index = 0)
{
ls.add(index);
index = s.indexOf(a, index + 1);
}
for(Object i : ls)
{
System.out.print(i + " ");
}
正好我前幾天做了一個瀏覽器實例,挺容易的其實。就用到了:
1.awtswing編界面和響應(yīng)。
2.網(wǎng)頁顯示區(qū)域是用JEditPane來顯示的。通過在上方設(shè)置一個JTextField輸入url以后,這里獲得url,然后直接setPage到url就行了。也不是太難。
其他沒啥如果樓主要代碼的話留下郵箱。
樓主編瀏覽器大概需要以下知識:
1.javase基礎(chǔ)
2.http協(xié)議大致傳輸過程
3.基礎(chǔ)的awtswing,以及窗口響應(yīng)布局等
4.淺顯的多線程知識