运行时可调用浏览器打开一个网页,网页地址在代码中的java代码怎么写?

Python015

运行时可调用浏览器打开一个网页,网页地址在代码中的java代码怎么写?,第1张

网页地址在代码中的java代码写法如下:

packagecom.test

importjava.lang.reflect.Method

//实现打开浏览器并跳到指定网址的类

publicclassBareBonesBrowserLaunch{

publicstaticvoidopenURL(Stringurl){

try{

browse(url)

}catch(Exceptione){

}

}

privatestaticvoidbrowse(Stringurl)throwsException{

//获取操作系统的名字

StringosName=System.getProperty("os.name","")

if(osName.startsWith("MacOS")){

//苹果的打开方式

ClassfileMgr=Class.forName("com.apple.eio.FileManager")

MethodopenURL=fileMgr.getDeclaredMethod("openURL",newClass[]{String.class})

openURL.invoke(null,newObject[]{url})

}elseif(osName.startsWith("Windows")){

//windows的打开方式。

Runtime.getRuntime().exec("rundll32url.dll,FileProtocolHandler"+url)

}else{

//UnixorLinux的打开方式

String[]browsers={"firefox","opera","konqueror","epiphany","mozilla","netscape"}

Stringbrowser=null

for(intcount=0count<browsers.length&&browser==nullcount++)

//执行代码,在brower有值后跳出,

//这里是如果进程创建成功了,==0是表示正常结束。

if(Runtime.getRuntime().exec(newString[]{"which",browsers[count]}).waitFor()==0)

browser=browsers[count]

if(browser==null)

thrownewException("Couldnotfindwebbrowser")

else

//这个值在上面已经成功的得到了一个进程。

Runtime.getRuntime().exec(newString[]{browser,url})

}

}

}

//主方法测试类

publicstaticvoidmain(String[]args){

Stringurl="http://iteye.blog.163.com/"

BareBonesBrowserLaunch.openURL(url)

}

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("输入网址:"))

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()

}

}