重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
网页地址在代码中的java代码写法如下:
网站建设哪家好,找成都创新互联!专注于网页设计、网站建设、微信开发、成都微信小程序、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了电白免费建站欢迎大家使用!
package com.test;
import java.lang.reflect.Method;
//实现打开浏览器并跳到指定网址的类
public class BareBonesBrowserLaunch {
public static void openURL(String url) {
try {
browse(url);
} catch (Exception e) {
}
}
private static void browse(String url) throws Exception {
//获取操作系统的名字
String osName = System.getProperty("os.name", "");
if (osName.startsWith("Mac OS")) {
//苹果的打开方式
Class fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class });
openURL.invoke(null, new Object[] { url });
} else if (osName.startsWith("Windows")) {
//windows的打开方式。
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
} else {
// Unix or Linux的打开方式
String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
String browser = null;
for (int count = 0; count browsers.length browser == null; count++)
//执行代码,在brower有值后跳出,
//这里是如果进程创建成功了,==0是表示正常结束。
if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0)
browser = browsers[count];
if (browser == null)
throw new Exception("Could not find web browser");
else
//这个值在上面已经成功的得到了一个进程。
Runtime.getRuntime().exec(new String[] { browser, url });
}
}
}
//主方法 测试类
public static void main(String[] args) {
String url = "";
BareBonesBrowserLaunch.openURL(url);
}
java浏览器开发,其实很简单, 使用JavaFX的WebView组件即可.(支持html5); 也可以在swing里使用JFXPanel然后添加WebView;
效果图如下
参考代码如下(java8+win10 x64 编写,测试)
import javafx.application.Application;
import javafx.concurrent.Worker.State;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.web.*;
import javafx.stage.Stage;
public class WebViewTest extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
//顶部
HBox hbox=new HBox(8);
Label labeAddr=new Label("地址");
TextField tfAddr = new TextField();
tfAddr.setMinWidth(500);
tfAddr.setText("");
Button btnGo = new Button("Go转到");
Button btnGoBack=new Button("-");
Button btnH=new Button("-");
TextField tfSerch = new TextField();
Button btnSerch= new Button("捜");
hbox.getChildren().addAll(labeAddr,tfAddr,btnGoBack,btnH,btnGo,tfSerch,btnSerch);
hbox.setPadding(new Insets(5));
//中间
WebView wv = new WebView();
WebEngine we = wv.getEngine();
we.getLoadWorker().stateProperty().addListener((ob, ov, nv) - {
if(nv==State.SCHEDULED) {
tfAddr.setText(we.getLocation());//
}
});
//底部
Label labelBottom = new Label();
labelBottom.textProperty().bind(we.getLoadWorker().messageProperty());//底下的信息显示
BorderPane root = new BorderPane();
root.setTop(hbox);
root.setCenter(wv);
root.setBottom(labelBottom);
Scene scene = new Scene(root, 900, 600);
primaryStage.setTitle("JavaFX 雪飞潇潇 web浏览器");
primaryStage.setScene(scene);
primaryStage.show();
btnGo.setOnAction(e - {
we.load(tfAddr.getText().trim());
});
btnGoBack.setOnAction(e-{
we.executeScript("history.back()");//执行JavaScript,后退
});
btnH.setOnAction(e-{
we.executeScript("history.forward()");//执行JavaScript,前进
});
//搜索
btnSerch.setOnAction(e-{
we.load(""+tfSerch.getText());
});
}
}
3.WebBrowser.java
package CH04.源程序;
/*
**网页浏览器主程序
**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 ();
//建立网页显示界面
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 ("前进");
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("前进");
JButton picView = new JButton("查看源代码");
JButton picExit = new JButton("退出");
JLabel label=new JLabel ("地址");
JButton button=new JButton ("转向");
Box adress=Box.createHorizontalBox ();
//ArrayList对象,用来存放历史地址
private ArrayList history=new ArrayList();
//整型变量,表示历史地址的访问顺序
private int historyIndex;
/**
**构造函数
**初始化图形用户界面
*/
public WebBrowser(){
setTitle ("网页浏览器");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//为jEditorPane1添加事件侦听
jEditorPane1.addHyperlinkListener (this);
//为组件fileMenu设置热键‘F’
fileMenu.setMnemonic('F');
saveAsItem.setMnemonic ('S');
//为“另存为”组件设置快捷键为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 ();
//设置大小
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);
//为组件添加事件监听
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);
}
/**
**实现监听器接口的actionPerformed函数
*/
public void actionPerformed(ActionEvent e) {
String url = "";
//点击转向按钮
if (e.getSource() == button){
//获得地址栏的内容
url=jurl.getText ();
//url不为“”,并且以“http://”开头
if(url.length ()0url.startsWith ("http://")){
try {
//JEditorPane组件显示url的内容链接
jEditorPane1.setPage (url);
//将url的内容添加到ArrayList对象history中
history.add(url);
//historyIndex的数值设为history对象的长度-1
historyIndex=history.size()-1;
//重新布局
jEditorPane1.setEditable(false); //add by copy editor :)
jEditorPane1.revalidate ();
}
catch(Exception ex) {
//如果链接显示失败,则弹出选择对话框“无法打开该搜索页”
JOptionPane.showMessageDialog (WebBrowser.this,"无法打开该搜索页","网页浏览器",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,"无法打开该搜索页","网页浏览器",JOptionPane.ERROR_MESSAGE);
}
}
//没有输入url,即url为空
else if(url.length ()==0){
JOptionPane.showMessageDialog (WebBrowser.this,"请输入链接地址","网页浏览器",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,"无法打开该搜索页","网页浏览器",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,"无法打开该搜索页","网页浏览器",JOptionPane.ERROR_MESSAGE);
}
}
else if(url.length ()==0){
JOptionPane.showMessageDialog (WebBrowser.this,"请输入链接地址","网页浏览器",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,"请输入链接地址","网页浏览器",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){
}
}
//前进
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 ("")) {
//根据url,获得源代码
getHtmlSource (url);
//生成显示源代码的框架对象
ViewSourceFrame vsframe = new ViewSourceFrame (htmlSource);
vsframe.setBounds (0,0,800,500);
vsframe.setVisible(true);
}
else {
JOptionPane.showMessageDialog (WebBrowser.this,"请输入链接地址","网页浏览器",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 + " 已经被保存至"+ 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 (),"网页浏览器",JOptionPane.ERROR_MESSAGE);
}
catch(Exception ex) {
JOptionPane.showMessageDialog ((Component) null,ex.toString (),"网页浏览器",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 (),"网页浏览器",JOptionPane.ERROR_MESSAGE);
}
catch(Exception e) {
JOptionPane.showMessageDialog (WebBrowser.this,e.toString (),"网页浏览器",JOptionPane.ERROR_MESSAGE);
}
}
/**
**实现监听器接口的hyperlinkUpdate函数
*/
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);
}
}
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.DefaultStyledDocument;
//HTTP连接与浏览
public class HTTPBrowser extends JFrame{
JTextField jtfAddress; //输入html文件地址或网址
JTextPane jtpShow; //显示页面
JTextArea jtaSource; //显示HTML源文件
public HTTPBrowser(){
super("HTTP连接与浏览"); //调用父类构造函数
jtfAddress=new JTextField(30); //实例化地址输入框
jtpShow=new JTextPane(); //实例化显示内容框
jtaSource=new JTextArea();
JPanel p1=new JPanel(); //实例化面板
JSplitPane spane=new JSplitPane(JSplitPane.VERTICAL_SPLIT); //实例化分隔面板
p1.add(new JLabel("地址")); //增加组件到面板上
p1.add(jtfAddress);
spane.add(new JScrollPane(jtpShow),JSplitPane.TOP);
spane.add(new JScrollPane(jtaSource),JSplitPane.BOTTOM);
spane.setDividerLocation(130); //设置分隔位置
spane.setDividerSize(2); //设置分隔栏尺寸
Container container=getContentPane(); //得到容器
container.add(p1,BorderLayout.NORTH); //增加组件到容器上
container.add(spane,BorderLayout.CENTER);
jtfAddress.addActionListener(new ShowHTMLListener()); //输入地址文本域事件处理
setSize(380,300); //设置窗口尺寸
setVisible(true); //设置窗口可视
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序
}
class ShowHTMLListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
try{
URL address=new URL(jtfAddress.getText()); //得到HTML页面的URL地址
jtpShow.setContentType("text/html"); //设置内容格式
jtpShow.setPage(address); //设置显示页面
BufferedReader in= new BufferedReader(new InputStreamReader(address.openStream())); //获取输入流
String line;
StringBuffer content = new StringBuffer(); //文件内容
while ((line = in.readLine()) != null) { //读取文件
content.append(line+"\n");
}
jtaSource.setText(new String(content)); //设置显示文本
in.close(); //关闭输入流
}
catch (Exception ex){
ex.printStackTrace(); //输出出错信息
}
}
}
public static void main(String[] args){
new HTTPBrowser();
}
}
这还有一个
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
//html浏览器
public class HTTPBrowserDemo extends JFrame{
JTextField jtfAddress; //输入html文件地址或网址
JButton jbGo; //转到文件按钮
JTextPane jtpShow; //显示文件
JLabel jlInfo; //提示信息
public HTTPBrowserDemo(){
super("html浏览器"); //调用父类构造函数
jtfAddress=new JTextField(20); //实例化地址输入框
jbGo=new JButton("转到"); //实例化转向按钮
jtpShow=new JTextPane(); //实例化显示内容框
jlInfo=new JLabel(); //实例化信息提示标签
JPanel panel=new JPanel(); //实例化面板
panel.add(new JLabel("地址")); //增加组件到面板上
panel.add(jtfAddress);
panel.add(jbGo);
JScrollPane jsp=new JScrollPane(jtpShow); //实例化滚动窗体
Container container=getContentPane(); //得到容器
container.add(panel,BorderLayout.NORTH); //增加组件到容器上
container.add(jsp,BorderLayout.CENTER);
container.add(jlInfo,BorderLayout.SOUTH);
jbGo.addActionListener(new ShowHTMLListener()); //事件处理,发生按钮点击时显示页面内容
jtfAddress.addActionListener(new ShowHTMLListener());
setSize(350,280); //设置窗口尺寸
setVisible(true); //设置窗口可视
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序
}
class ShowHTMLListener implements ActionListener { //显示页面内容事件处理
public void actionPerformed(ActionEvent event) {
try{
jlInfo.setText("正在连接..."); //显示提示信息
URL address=new URL(jtfAddress.getText()); //得到HTML页面的URL地址
jtpShow.setPage(address); //设置显示页面
jlInfo.setText("完成");
}
catch (Exception ex){
jlInfo.setText("连接出错");
ex.printStackTrace(); //输出出错信息
}
}
}
public static void main(String[] args){
new HTTPBrowserDemo();
}
}