package com.rain;
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
{
//建立菜单栏
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 forwardItem=new JMenuItem("前进");
JMenuItem backItem=new JMenuItem("后退");
JMenu viewMenu=new JMenu("视图(V)");
JMenuItem fullscreenItem=new JMenuItem("全屏(U)");
JMenuItem sourceItem=new JMenuItem("查看源码(C)");
JMenuItem reloadItem=new JMenuItem("刷新(R)");
// 建立工具栏
JToolBar toolBar1=new JToolBar();
//建立工具栏中的按钮组件
JButton SaveButton=new JButton("另存为");
JButton ForwardButton=new JButton("前进");
JButton BackButton=new JButton("后退");
JButton ViewButton=new JButton("查看源代码");
JButton ExitButton=new JButton("退出");
//建立工具栏用来显示地址栏
JToolBar toolBar2=new JToolBar();
//建立地址栏中的组件
JLabel label=new JLabel("地址");
JTextField jurl=new JTextField(50);
JButton turnbutton=new JButton("转向");
JButton RestoreButton=new JButton("窗口还原");
// 建立网页显示界面
JEditorPane jEditorPane=new JEditorPane();//网页文本框
JScrollPane scrollPane=new JScrollPane(jEditorPane);
JFileChooser chooser=new JFileChooser();//构造文件选择器
JFileChooser chooser1=new JFileChooser();
String htmlSource;
JWindow window=new JWindow(WebBrowser.this);//使用指定的所有者框架创建窗口
Toolkit toolkit=Toolkit.getDefaultToolkit();//获取默认工具包
Box box=Box.createHorizontalBox();//创建一个从左到右显示其组件
//ArrayList对象,用来存放历史地址
private ArrayList history=new ArrayList();
//整型变量,表示历史地址的访问顺序
private int historyIndex;
/*构造函数
* 初始化图形用户界面*/
public WebBrowser()
{
setTitle ("网页浏览器");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口,不写的话,界面是没了,但程序还驻留在 内存中没有结束。
setResizable(false);//不能手动改变框架大小
//为jEditorPane添加事件侦听
jEditorPane.addHyperlinkListener(this);
jMenuBar1.add(fileMenu);
jMenuBar1.add(editMenu);
jMenuBar1.add(viewMenu);
setJMenuBar(jMenuBar1);//将菜单栏加入到框架中
//将菜单项saveAsItem加入到菜单组fileMenu中
fileMenu.add(saveAsItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
fileMenu.setMnemonic('F');//为组件fileMenu设置热键'F'
saveAsItem.setMnemonic('S');
saveAsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK)); //为"另存为"组件设置快捷键ctrl+s
exitItem.setMnemonic('Q');
exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,InputEvent.CTRL_MASK));
editMenu.add(backItem);
editMenu.add(forwardItem);
editMenu.setMnemonic('E');
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));
viewMenu.add(fullscreenItem);
viewMenu.add(sourceItem);
viewMenu.addSeparator();
viewMenu.add(reloadItem);
viewMenu.setMnemonic('V');
fullscreenItem.setMnemonic('U');
fullscreenItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U,InputEvent.CTRL_MASK));
sourceItem.setMnemonic('C');
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));
//在工具栏中添加按钮组件
toolBar1.add(SaveButton);
toolBar1.addSeparator();
toolBar1.add(ForwardButton);
toolBar1.addSeparator();
toolBar1.add(BackButton);
toolBar1.addSeparator();
toolBar1.add(ViewButton);
toolBar1.addSeparator();
toolBar1.add(ExitButton);
box.add(label);
box.add(jurl);
box.add(turnbutton);
toolBar2.add(box);
Container contentPane=getContentPane();//建立一个contaniner用来装各种组件
scrollPane.setPreferredSize(new Dimension(100,400));//设置大小
contentPane.add(scrollPane,BorderLayout.SOUTH);
contentPane.add(toolBar1,BorderLayout.NORTH);
contentPane.add(toolBar2,BorderLayout.CENTER);
//为组件添加事件监听
saveAsItem.addActionListener(this);
forwardItem.addActionListener(this);
backItem.addActionListener(this);
exitItem.addActionListener(this);
fullscreenItem.addActionListener(this);
sourceItem.addActionListener(this);
reloadItem.addActionListener(this);
SaveButton.addActionListener(this);
ForwardButton.addActionListener(this);
BackButton.addActionListener(this);
ViewButton.addActionListener(this);
ExitButton.addActionListener(this);
jurl.addActionListener(this);
turnbutton.addActionListener(this);
}
/*实现监听器接口的actionPerformed函数*/
public void actionPerformed(ActionEvent e)
{
String url="";
//点击转向按钮
if(e.getSource()==turnbutton)
{
//获得地址栏的内容
url=jurl.getText();//getText()表示将当前文本作为字符串返回
//url不为"",并且以"http://"开头
if(url.length()>0&&url.startsWith("http://"))
{
try
{
//JEditorPane组件显示url的内容链接
jEditorPane.setPage(url);
//将url的内容添加到ArrayList对象history中
history.add(url);
//historyIndex的数值设为history对象的长度-1
historyIndex=history.size()-1;
//设置成非编辑状态
jEditorPane.setEditable(false);
//重新布局
jEditorPane .revalidate();//revalidate()表示因为性能原因而被重写。
}
catch(Exception ex)
{
//如果链接显示失败,则弹出选择对话框"无法打开搜索页"
JOptionPane.showMessageDialog(WebBrowser.this,"无法打开该搜索页");
}
}
//url不为"",并且不以"http://"开头
else if(url.length()>0&&!url.startsWith("http://"))
{
url="http://"+url;
try
{
jEditorPane.setPage(url );
history.add(url);
historyIndex=history.size()-1;
jEditorPane.setEditable(false);
jEditorPane.revalidate();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(WebBrowser.this,"无法打开该搜索页");
}
}
//没有输入url,即url为空
else if(url.length()==0)
{
JOptionPane.showMessageDialog(WebBrowser.this,"请输入链接地址");
}
}
//输入地址后按回车键
if(e.getSource()==jurl)
{
url=jurl.getText();
if(url.length()>0&&url.startsWith("http://"))
{
try
{
jEditorPane.setPage(url);
history.add(url);
historyIndex=history.size()-1;
jEditorPane.setEditable(false);
jEditorPane.revalidate();
jurl.setMaximumSize(jurl.getPreferredSize());//将此组件的最大大小设置为一个常量值。
}
catch(Exception ex)
{
//如果链接显示失败,则弹出选择对话框"无法打开搜索页"
JOptionPane.showMessageDialog(WebBrowser.this,"无法打开该搜索页");
}
}
//url不为"",并且不以"http://"开头
else if(url.length()>0&&!url.startsWith("http://"))
{
url="http://"+url;
try
{
jEditorPane.setPage(url);
history.add(url);
historyIndex=history.size()-1;
jEditorPane.setEditable(false);
jEditorPane.revalidate();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(WebBrowser.this,"无法打开该搜索页");
}
}
//没有输入url,即url为空
else if(url.length()==0)
{
JOptionPane.showMessageDialog(WebBrowser.this,"请输入链接地址");
}
}
//另存为...
else if(e.getSource()==SaveButton||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,"请输入链接地址");
}
}
//退出
else if(e.getSource()==exitItem||e.getSource()==ExitButton)
{
System.exit(0);
}
//前进
else if(e.getSource()==forwardItem||e.getSource()==ForwardButton)
{
historyIndex++;
if(historyIndex>=history.size())
historyIndex=history.size()-1;
url=jurl.getText();
try
{
//获得history对象中本地址之前访问的地址
url=(String)history.get(historyIndex);
jEditorPane.setPage(url);
//将文本修改成指定字符串
jurl.setText(url.toString());//toString()表示将类型转换成一个字符串。
jEditorPane.setEditable(false);
jEditorPane.revalidate();
}
catch(Exception ex) {}
}
//后退
else if(e.getSource()==backItem||e.getSource()==BackButton)
{
historyIndex--;
if(historyIndex<0) historyIndex=0;
url=jurl.getText();
try
{
url=(String)history.get(historyIndex);
jEditorPane.setPage(url);
jurl.setText(url.toString());
jEditorPane.setEditable(false);
jEditorPane.revalidate();
}
catch(Exception ex) {}
}
//全屏
else if(e.getSource()==fullscreenItem)
{
boolean add_RestoreButton=true;
//获得屏幕大小
Dimension size=Toolkit.getDefaultToolkit().getScreenSize();
Container content=window.getContentPane();
content.add(toolBar2,"North");
content.add(scrollPane,"Center");
//button2为单击"全屏"后的还原按钮
if(add_RestoreButton=true)
{
toolBar2.add(RestoreButton);
}
//为button2添加事件
RestoreButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
WebBrowser.this.setEnabled(true);//设置按钮是否可被激活
window.remove(toolBar2);
window.remove(toolBar1);
window.remove(scrollPane);
window.setVisible(false);//设置窗口不可见
scrollPane.setPreferredSize(new Dimension(100,500));
getContentPane().add(scrollPane,BorderLayout.SOUTH);
getContentPane().add(toolBar2,BorderLayout.CENTER);
getContentPane().add(toolBar1,BorderLayout.NORTH);
/*toolBar2.remove(RestoreButton);*/
pack();//布置容器,让它使用显示其内容所需的最小空间。
}
});
window.setSize(size);
window.setVisible(true);
}
//查看源文件
else if(e.getSource()==sourceItem||e.getSource()==ViewButton)
{
url=jurl.getText().toString().trim();
if(url.length()>0&&!url.startsWith("http://"))
{
url="http://"+url;
}
if(!url.equals(""))
{
//根据url,获得源代码
getHtmlSource(url);
//生成显示源代码的框架对象
ViewSourceFrame vsframe=new ViewSourceFrame(htmlSource);
vsframe.setBounds(0,0,800,500);
vsframe.setVisible(true);
}
else
{
JOptionPane.showMessageDialog(WebBrowser.this,"请输入链接地址");
}
}
//刷新
else if(e.getSource()==reloadItem)
{
url=jurl.getText();
if(url.length()>0&&url.startsWith("http://"))
{
try
{
jEditorPane.setPage(url);
jEditorPane.setEditable(false);
jEditorPane.revalidate();
}
catch(Exception ex) {}
}
else if(url.length()>0&&!url.startsWith("http://"))
{
url="http://"+url;
try
{
jEditorPane.setPage(url);
jEditorPane.setEditable(false);
jEditorPane.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+"已经被保存至"+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());
}
catch(Exception ex)
{
JOptionPane.showMessageDialog((Component)null,ex.toString());
}
}
};
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)//抛出这一异常指示出现了错误的 URL。或者在规范字符串中找不到任何合法协议,或者无法分析字符串。
{
JOptionPane.showMessageDialog(WebBrowser.this,muex.toString());
}
catch(Exception e)
{
JOptionPane.showMessageDialog(WebBrowser.this,e.toString());
}
}
/*实现监听器接口hyperlinkUpdate函数*/
public void hyperlinkUpdate(HyperlinkEvent e)
{
try
{
if(e.getEventType()==HyperlinkEvent.EventType.ACTIVATED)//激活类型
jEditorPane.setPage(e.getURL());
}
catch(Exception ex){/*ex.printStackTrace(System.err);*/}
}
public static void main(String [] args)
{
/*try
{
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
}
catch(Exception e){}*/
WebBrowser webBrowser=new WebBrowser();
webBrowser.pack();
webBrowser.setVisible(true);
}
package com.rain;
import java.awt.*;
import javax.swing.*;
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.util.*;
class ViewSourceFrame extends JFrame implements ActionListener
{
JPanel contentPane;
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
Border border1;
JButton closebutton=new JButton();
JButton savebutton=new JButton();
JScrollPane jScrollPanel=new JScrollPane();
JTextArea jTextArea1 =new JTextArea();
String htmlSource;
private Object SA;
/*构造函数,初始化图形用户界面*/
public ViewSourceFrame(String htmlSource)
{
this.htmlSource=htmlSource;
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
setSize(new Dimension(600,500));
setTitle("源代码");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
contentPane=(JPanel)getContentPane();
contentPane.setLayout(new BorderLayout());
panel2.setLayout(new FlowLayout());
savebutton.setText("保存");
closebutton.setText("退出");
closebutton.addActionListener(this);
savebutton.addActionListener(this);
jScrollPanel.getViewport().add(jTextArea1,null);
border1=BorderFactory.createEmptyBorder(4,4,4,4);
panel1.setLayout(new BorderLayout());
panel1.setBorder(border1);
panel1.add(jScrollPanel,BorderLayout.CENTER);
contentPane.add(panel1,BorderLayout.CENTER);
panel2.add(savebutton);
panel2.add(closebutton);
contentPane.add(panel2,BorderLayout.SOUTH);
this.jTextArea1.setEditable(true);
this.jTextArea1.setText(this.htmlSource);
//设置光标的位置,将其移动到文本区第0个字符
this.jTextArea1.setCaretPosition(0);
}
/*实现监听器接口的actionPerformed函数*/
public void actionPerformed(ActionEvent e)
{
String url="";
if(e.getSource()==closebutton)
{
dispose();
}
else if(e.getSource()==savebutton)
{
JFileChooser fc=new JFileChooser();
int returnVal=fc.showSaveDialog(ViewSourceFrame.this);
File saveFile=fc.getSelectedFile();
try
{
FileWriter writeOut=new FileWriter(saveFile);
writeOut.write(jTextArea1.getText());
writeOut.close();
}
catch(IOException ex)
{
System.out.println("保存失败");
}
}
}
}