Acessar o browser a partir de um componente swing

Olá pessoal,
Eu preciso acessar uma página web a partir de um componente swing tipo O JTextField,
Problema eu digito o site no campo texto e tipo com dois cliques ele me abra a pagina desse site.
Isso é possível?
Se possível a alguma desvantagem em fazer isso?Tipo quando troco de ambiente (Linux/Windows)?

Tem algum exemplo que eu possa acessa?

Até +++

o JEditorPane faz isso se nao me engano, tem um exemplo de browser no livro dos deitel, a 4ª edição, quem tiver ai posta hehe

 // 
 // This program uses a JEditorPane to display the
 // contents of a file on a Web server.

// Java core packages
 import java.awt.*;
 import java.awt.event.*;
 import java.net.*;
 import java.io.*;

 // Java extension packages
 import javax.swing.*;
 import javax.swing.event.*;

 public class ReadServerFile extends JFrame {
 private JTextField enterField;
 private JEditorPane contentsArea;

 // set up GUI
 public ReadServerFile()
 {
 super( "Simple Web Browser" );

 Container container = getContentPane();

 // create enterField and register its listener
 enterField = new JTextField( "Enter file URL here" );

 enterField.addActionListener(

 new ActionListener() {

 // get document specified by user
 public void actionPerformed( ActionEvent event )
 {
 getThePage( event.getActionCommand() );
 }

 } // end anonymous inner class

 ); // end call to addActionListener

 container.add( enterField, BorderLayout.NORTH );

 // create contentsArea and register HyperlinkEvent listener
 contentsArea = new JEditorPane();
 contentsArea.setEditable( false );

 contentsArea.addHyperlinkListener(

 new HyperlinkListener() {

 // if user clicked hyperlink, go to specified page
 public void hyperlinkUpdate( HyperlinkEvent event )
 {
 if ( event.getEventType() ==
 HyperlinkEvent.EventType.ACTIVATED )
 getThePage( event.getURL().toString() );
 }

 } // end anonymous inner class

 ); // end call to addHyperlinkListener

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

 setSize( 400, 300 );
 setVisible( true );
 }

 // load document; change mouse cursor to indicate status
 private void getThePage( String location )
 {
 // change mouse cursor to WAIT_CURSOR
 setCursor( Cursor.getPredefinedCursor(
 Cursor.WAIT_CURSOR ) );

 // load document into contentsArea and display location in
 // enterField
 try {
 contentsArea.setPage( location );
 enterField.setText( location );
 }

 // process problems loading document
 catch ( IOException ioException ) {
 JOptionPane.showMessageDialog( this,
 "Error retrieving specified URL",
 "Bad URL", JOptionPane.ERROR_MESSAGE );
 }

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

 // begin application execution
 public static void main( String args[] )
 {
ReadServerFile application = new ReadServerFile();
 application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
} // end class ReadServerFile

Taí…

ola esse ai…

/*
 * Created on 01/02/2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package outroPacote;

import java.applet.AppletContext;
import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 * @author junior
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class SiteSelector extends JApplet{
	private Hashtable sites;
	private Vector sitesNames;
	private JList siteChooser;

	public void init() {
		sites = new Hashtable();
		sitesNames = new Vector();
		
		//obtem parametro do documento HTML
		getSitesDoHTMLParameters();
		
		Container c = getContentPane();
		c.add(new JLabel("Choose a site to browse"), BorderLayout.NORTH);
		
		siteChooser = new JList( sitesNames );
		
		siteChooser.addListSelectionListener(
				new ListSelectionListener() {
					
					//vai pr o site q o usuario selecionou
					public void valueChanged( ListSelectionEvent event) {
						
						//obtem o nome do site selecionado
						Object obj = siteChooser.getSelectedValue();
						
						// usa o nome do site p/ localizar url correspondente
						URL newDocument = ( URL ) sites.get( obj );
						
						// obtem referencia pr o container de applet
						AppletContext browser = getAppletContext();
						
						//diz pr o container de applets pr mudar de pagina
						browser.showDocument(newDocument);
					}
				}
		);
		c.add(new JScrollPane(siteChooser), BorderLayout.CENTER);
		
	}
	
	public void getSitesDoHTMLParameters() {
		/* 
		 * procura os parametros do applet no documento HTML 
		 * e adiciona os sites no Hashtable 
		*/
		String title , location;
		URL url;
		int cont = 0;
		
		//obtem o titulo do primeiro site
		title = getParameter("title"+ cont);
		
		//repete o laço ate q ñ haja + parametros no documento HTML
		while (title != null) {
			//obtem a posicao do site  
			location = getParameter("location"+ cont);
			 
			 try {
			 	//converte a posicao em um URL
			 	url = new URL (location); 
			 	
			 	//coloca o titulo/url na Hashtable
			 	sites.put(title, url);
			 	
			 	//coloca titulo no Vector
			 	sitesNames.add(title);
			 }
			 catch (MalformedURLException urlException) {
			 	urlException.printStackTrace();
			 }
			 cont++;
			 
			 //obtem o titulo do proximo site
			 title = getParameter("title"+ cont);
		}
	}
}

tem q ter o html tbm
<html>
<title>Site Selector</title>
<body>
<applet code = “SiteSelector.class” width = “300” height = “75”>
<param name = “title0” value = “Java Home Page”>
<param name = “location0” value = “http://java.sun.com/”>
<param name = “title1” value = “Deitel”>
<param name = “location1” value = “http://www.deitel.com/”>
<param name = “title2” value = “JGuru”>
<param name = “location2” value = “http://www.jGuru.com/”>
<param name = “title3” value = “Java World”>
<param name = “location3” value = “http://www.javaworld.com/”>
</applet>
</body>
</html> :grin:

Valeu pela força galera!

[quote=“AaroeiraA”][code]
//
// This program uses a JEditorPane to display the
// contents of a file on a Web server.

// Java core packages
import java.awt.;
import java.awt.event.
;
import java.net.;
import java.io.
;

// Java extension packages
import javax.swing.;
import javax.swing.event.
;

public class ReadServerFile extends JFrame {
private JTextField enterField;
private JEditorPane contentsArea;

// set up GUI
public ReadServerFile()
{
super( "Simple Web Browser" );

Container container = getContentPane();

// create enterField and register its listener
enterField = new JTextField( "Enter file URL here" );

enterField.addActionListener(

new ActionListener() {

// get document specified by user
public void actionPerformed( ActionEvent event )
{
getThePage( event.getActionCommand() );
}

} // end anonymous inner class

); // end call to addActionListener

container.add( enterField, BorderLayout.NORTH );

// create contentsArea and register HyperlinkEvent listener
contentsArea = new JEditorPane();
contentsArea.setEditable( false );

contentsArea.addHyperlinkListener(

new HyperlinkListener() {

// if user clicked hyperlink, go to specified page
public void hyperlinkUpdate( HyperlinkEvent event )
{
if ( event.getEventType() ==
HyperlinkEvent.EventType.ACTIVATED )
getThePage( event.getURL().toString() );
}

} // end anonymous inner class

); // end call to addHyperlinkListener

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

setSize( 400, 300 );
setVisible( true );
}

// load document; change mouse cursor to indicate status
private void getThePage( String location )
{
// change mouse cursor to WAIT_CURSOR
setCursor( Cursor.getPredefinedCursor(
Cursor.WAIT_CURSOR ) );

// load document into contentsArea and display location in
// enterField
try {
contentsArea.setPage( location );
enterField.setText( location );
}

// process problems loading document
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"Error retrieving specified URL",
"Bad URL", JOptionPane.ERROR_MESSAGE );
}

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

// begin application execution
public static void main( String args[] )
{
ReadServerFile application = new ReadServerFile();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
} // end class ReadServerFile
[/code]

Taí…[/quote]

Teria como eu abrir um brouse normal passando o endereço que foi digitado no JTextField?

Sidinei,

Para você executar um comando através de uma aplicação Java você deve usar a classe Runtime. Esta classe tem o método static getRuntime() que retorna o objeto Runtime da aplicação Java em execução. Com este objeto, você pode usar o método exec() para executar o comando que você quiser. Este método é sobrecarregado. Verifique a API.

Eu fiz uma classe para teste. Veja só:

import javax.swing.JOptionPane;

public class Teste &#123;

	public static void main&#40;String args&#91;&#93;&#41; &#123;
		Runtime runtime = Runtime.getRuntime&#40;&#41;;
		String comando = &quot;C&#58;\\Program Files\\Mozilla Firefox\\firefox.exe &quot;;
		comando += JOptionPane.showInputDialog&#40;&quot;Digite a url&quot;&#41;;
		try &#123;
			runtime.exec&#40;comando&#41;;
		&#125; catch&#40;Exception e&#41; &#123;
			e.printStackTrace&#40;&#41;;
		&#125;
		System.exit&#40;0&#41;;
	&#125;
&#125;

Se você passar só o URL ele não consegue criar um processo para executar o comando que você passou. Então eu passei o caminho do executável mais a página que ele irá abrir.

Faça um teste.

[quote=“AaroeiraA”]Sidinei,

Para você executar um comando através de uma aplicação Java você deve usar a classe Runtime. Esta classe tem o método static getRuntime() que retorna o objeto Runtime da aplicação Java em execução. Com este objeto, você pode usar o método exec() para executar o comando que você quiser. Este método é sobrecarregado. Verifique a API.

Eu fiz uma classe para teste. Veja só:

import javax.swing.JOptionPane;

public class Teste &#123;

	public static void main&#40;String args&#91;&#93;&#41; &#123;
		Runtime runtime = Runtime.getRuntime&#40;&#41;;
		String comando = &quot;C&#58;\\Program Files\\Mozilla Firefox\\firefox.exe &quot;;
		comando += JOptionPane.showInputDialog&#40;&quot;Digite a url&quot;&#41;;
		try &#123;
			runtime.exec&#40;comando&#41;;
		&#125; catch&#40;Exception e&#41; &#123;
			e.printStackTrace&#40;&#41;;
		&#125;
		System.exit&#40;0&#41;;
	&#125;
&#125;

Se você passar só o URL ele não consegue criar um processo para executar o comando que você passou. Então eu passei o caminho do executável mais a página que ele irá abrir.

Faça um teste.[/quote]

Valeu mesmo pela ajuda

Obrigado

Abraços

E como é que vc pode descobrir o caminho relativo ao invés de colocar ele fixo: "C:\Program Files\Mozilla Firefox\firefox.exe "?

[]s,

olha pessoal, c vcs estiverem usando ®Windows, use o comando start

por exemplo, para abrir uma pagina no navegador padrão, no windows, vc pode usar:

 start http&#58;//www.portaljava.com

Um exemplo bem simples:

import java.io.IOException;
import javax.swing.JOptionPane;

public class CarregaURL &#123;
    public static void main&#40;String&#91;&#93; args&#41; &#123;
        String comando = JOptionPane.showInputDialog&#40;&quot;Digite sua URL&quot;&#41;;
        try &#123;
            Runtime.getRuntime&#40;&#41;.exec&#40;&quot;start &quot; + comando&#41;;
        &#125; catch &#40;IOException e&#41; &#123;
            e.printStackTrace&#40;&#41;;
        &#125;
    &#125;
&#125;

Espero q seja útil,

Ederson

start funciona no 98, mas no XP:

[quote]java.io.IOException: CreateProcess: start c:\drwtsn32.log error=2
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Win32Process.java:66)
at java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.exec(Runtime.java:566)
at java.lang.Runtime.exec(Runtime.java:428)
at java.lang.Runtime.exec(Runtime.java:364)
at java.lang.Runtime.exec(Runtime.java:326)
at A.main(A.java:6)
[/quote]

Achei essa página: http://mindprod.com/jgloss/exec.html, mas não consegui fazer funcionar também (sem erro, mas não abriu o notepad).

http://jdic.dev.java.net