Acessar o browser a partir de um componente swing

11 respostas
S

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é +++

11 Respostas

M

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

A
// 
 // 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í…

E

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 = “<a href="http://java.sun.com/">http://java.sun.com/</a>”>

<param name = “title1” value = “Deitel”>

<param name = “location1” value = “<a href="http://www.deitel.com/">http://www.deitel.com/</a>”>

<param name = “title2” value = “JGuru”>

<param name = “location2” value = “<a href="http://www.jGuru.com/">http://www.jGuru.com/</a>”>

<param name = “title3” value = “Java World”>

<param name = “location3” value = “<a href="http://www.javaworld.com/">http://www.javaworld.com/</a>”>

</applet>

</body>

</html>	 <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@14/assets/72x72/g.pngrin.png?v=9" title=":grin:" class="emoji" alt=":grin:">
S

Valeu pela força galera!

S
"AaroeiraA":
// 
 // 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 &#123;
 private JTextField enterField;
 private JEditorPane contentsArea;

 // set up GUI
 public ReadServerFile&#40;&#41;
 &#123;
 super&#40; &quot;Simple Web Browser&quot; &#41;;

 Container container = getContentPane&#40;&#41;;

 // create enterField and register its listener
 enterField = new JTextField&#40; &quot;Enter file URL here&quot; &#41;;

 enterField.addActionListener&#40;

 new ActionListener&#40;&#41; &#123;

 // get document specified by user
 public void actionPerformed&#40; ActionEvent event &#41;
 &#123;
 getThePage&#40; event.getActionCommand&#40;&#41; &#41;;
 &#125;

 &#125; // end anonymous inner class

 &#41;; // end call to addActionListener

 container.add&#40; enterField, BorderLayout.NORTH &#41;;

 // create contentsArea and register HyperlinkEvent listener
 contentsArea = new JEditorPane&#40;&#41;;
 contentsArea.setEditable&#40; false &#41;;

 contentsArea.addHyperlinkListener&#40;

 new HyperlinkListener&#40;&#41; &#123;

 // if user clicked hyperlink, go to specified page
 public void hyperlinkUpdate&#40; HyperlinkEvent event &#41;
 &#123;
 if &#40; event.getEventType&#40;&#41; ==
 HyperlinkEvent.EventType.ACTIVATED &#41;
 getThePage&#40; event.getURL&#40;&#41;.toString&#40;&#41; &#41;;
 &#125;

 &#125; // end anonymous inner class

 &#41;; // end call to addHyperlinkListener

 container.add&#40; new JScrollPane&#40; contentsArea &#41;,
 BorderLayout.CENTER &#41;;

 setSize&#40; 400, 300 &#41;;
 setVisible&#40; true &#41;;
 &#125;

 // load document; change mouse cursor to indicate status
 private void getThePage&#40; String location &#41;
 &#123;
 // change mouse cursor to WAIT_CURSOR
 setCursor&#40; Cursor.getPredefinedCursor&#40;
 Cursor.WAIT_CURSOR &#41; &#41;;

 // load document into contentsArea and display location in
 // enterField
 try &#123;
 contentsArea.setPage&#40; location &#41;;
 enterField.setText&#40; location &#41;;
 &#125;

 // process problems loading document
 catch &#40; IOException ioException &#41; &#123;
 JOptionPane.showMessageDialog&#40; this,
 &quot;Error retrieving specified URL&quot;,
 &quot;Bad URL&quot;, JOptionPane.ERROR_MESSAGE &#41;;
 &#125;

 setCursor&#40; Cursor.getPredefinedCursor&#40;
 Cursor.DEFAULT_CURSOR &#41; &#41;;
 &#125;

 // begin application execution
 public static void main&#40; String args&#91;&#93; &#41;
 &#123;
ReadServerFile application = new ReadServerFile&#40;&#41;;
 application.setDefaultCloseOperation&#40;
JFrame.EXIT_ON_CLOSE &#41;;
&#125;
&#125; // end class ReadServerFile

Taí...

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

A

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 = "C&#58;\\Program Files\\Mozilla Firefox\\firefox.exe ";
		comando += JOptionPane.showInputDialog&#40;"Digite a url"&#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.

S

“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 = "C&#58;\\Program Files\\Mozilla Firefox\\firefox.exe ";
		comando += JOptionPane.showInputDialog&#40;"Digite a url"&#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.

Valeu mesmo pela ajuda

Obrigado

Abraços

C

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

[]s,

E

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;"Digite sua URL"&#41;;
        try &#123;
            Runtime.getRuntime&#40;&#41;.exec&#40;"start " + comando&#41;;
        &#125; catch &#40;IOException e&#41; &#123;
            e.printStackTrace&#40;&#41;;
        &#125;
    &#125;
&#125;

Espero q seja útil,

Ederson

S

start funciona no 98, mas no XP:

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

</blockquote>

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

S

http://jdic.dev.java.net

Criado 14 de fevereiro de 2005
Ultima resposta 21 de fev. de 2005
Respostas 11
Participantes 8