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)?
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
AaroeiraAPJ
// // This program uses a JEditorPane to display the// contents of a file on a Web server.// Java core packagesimportjava.awt.*;importjava.awt.event.*;importjava.net.*;importjava.io.*;// Java extension packagesimportjavax.swing.*;importjavax.swing.event.*;publicclassReadServerFileextendsJFrame{privateJTextFieldenterField;privateJEditorPanecontentsArea;// set up GUIpublicReadServerFile(){super("Simple Web Browser");Containercontainer=getContentPane();// create enterField and register its listenerenterField=newJTextField("Enter file URL here");enterField.addActionListener(newActionListener(){// get document specified by userpublicvoidactionPerformed(ActionEventevent){getThePage(event.getActionCommand());}}// end anonymous inner class);// end call to addActionListenercontainer.add(enterField,BorderLayout.NORTH);// create contentsArea and register HyperlinkEvent listenercontentsArea=newJEditorPane();contentsArea.setEditable(false);contentsArea.addHyperlinkListener(newHyperlinkListener(){// if user clicked hyperlink, go to specified pagepublicvoidhyperlinkUpdate(HyperlinkEventevent){if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED)getThePage(event.getURL().toString());}}// end anonymous inner class);// end call to addHyperlinkListenercontainer.add(newJScrollPane(contentsArea),BorderLayout.CENTER);setSize(400,300);setVisible(true);}// load document; change mouse cursor to indicate statusprivatevoidgetThePage(Stringlocation){// change mouse cursor to WAIT_CURSORsetCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));// load document into contentsArea and display location in// enterFieldtry{contentsArea.setPage(location);enterField.setText(location);}// process problems loading documentcatch(IOExceptionioException){JOptionPane.showMessageDialog(this,"Error retrieving specified URL","Bad URL",JOptionPane.ERROR_MESSAGE);}setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));}// begin application executionpublicstaticvoidmain(Stringargs[]){ReadServerFileapplication=newReadServerFile();application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}// end class ReadServerFile
Taí…
E
EjuniorPJ
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 */packageoutroPacote;importjava.applet.AppletContext;importjava.awt.*;importjava.net.MalformedURLException;importjava.net.URL;importjava.util.*;importjavax.swing.*;importjavax.swing.event.ListSelectionEvent;importjavax.swing.event.ListSelectionListener;/** * @author junior * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */publicclassSiteSelectorextendsJApplet{privateHashtablesites;privateVectorsitesNames;privateJListsiteChooser;publicvoidinit(){sites=newHashtable();sitesNames=newVector();//obtem parametro do documento HTMLgetSitesDoHTMLParameters();Containerc=getContentPane();c.add(newJLabel("Choose a site to browse"),BorderLayout.NORTH);siteChooser=newJList(sitesNames);siteChooser.addListSelectionListener(newListSelectionListener(){//vai pr o site q o usuario selecionoupublicvoidvalueChanged(ListSelectionEventevent){//obtem o nome do site selecionadoObjectobj=siteChooser.getSelectedValue();// usa o nome do site p/ localizar url correspondenteURLnewDocument=(URL)sites.get(obj);// obtem referencia pr o container de appletAppletContextbrowser=getAppletContext();//diz pr o container de applets pr mudar de paginabrowser.showDocument(newDocument);}});c.add(newJScrollPane(siteChooser),BorderLayout.CENTER);}publicvoidgetSitesDoHTMLParameters(){/* * procura os parametros do applet no documento HTML * e adiciona os sites no Hashtable */Stringtitle,location;URLurl;intcont=0;//obtem o titulo do primeiro sitetitle=getParameter("title"+cont);//repete o laço ate q ñ haja + parametros no documento HTMLwhile(title!=null){//obtem a posicao do site location=getParameter("location"+cont);try{//converte a posicao em um URLurl=newURL(location);//coloca o titulo/url na Hashtablesites.put(title,url);//coloca titulo no VectorsitesNames.add(title);}catch(MalformedURLExceptionurlException){urlException.printStackTrace();}cont++;//obtem o titulo do proximo sitetitle=getParameter("title"+cont);}}}
// // This program uses a JEditorPane to display the// contents of a file on a Web server.// Java core packagesimportjava.awt.*;importjava.awt.event.*;importjava.net.*;importjava.io.*;// Java extension packagesimportjavax.swing.*;importjavax.swing.event.*;publicclassReadServerFileextendsJFrame{privateJTextFieldenterField;privateJEditorPanecontentsArea;// set up GUIpublicReadServerFile(){super("SimpleWebBrowser");Containercontainer=getContentPane();// create enterField and register its listenerenterField=newJTextField("EnterfileURLhere");enterField.addActionListener(newActionListener(){// get document specified by userpublicvoidactionPerformed(ActionEventevent){getThePage(event.getActionCommand());}}// end anonymous inner class);// end call to addActionListenercontainer.add(enterField,BorderLayout.NORTH);// create contentsArea and register HyperlinkEvent listenercontentsArea=newJEditorPane();contentsArea.setEditable(false);contentsArea.addHyperlinkListener(newHyperlinkListener(){// if user clicked hyperlink, go to specified pagepublicvoidhyperlinkUpdate(HyperlinkEventevent){if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED)getThePage(event.getURL().toString());}}// end anonymous inner class);// end call to addHyperlinkListenercontainer.add(newJScrollPane(contentsArea),BorderLayout.CENTER);setSize(400,300);setVisible(true);}// load document; change mouse cursor to indicate statusprivatevoidgetThePage(Stringlocation){// change mouse cursor to WAIT_CURSORsetCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));// load document into contentsArea and display location in// enterFieldtry{contentsArea.setPage(location);enterField.setText(location);}// process problems loading documentcatch(IOExceptionioException){JOptionPane.showMessageDialog(this,"ErrorretrievingspecifiedURL","BadURL",JOptionPane.ERROR_MESSAGE);}setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));}// begin application executionpublicstaticvoidmain(Stringargs[]){ReadServerFileapplication=newReadServerFile();application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}// end class ReadServerFile
Taí...
Teria como eu abrir um brouse normal passando o endereço que foi digitado no JTextField?
A
AaroeiraAPJ
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ó:
importjavax.swing.JOptionPane;publicclassTeste{publicstaticvoidmain(Stringargs[]){Runtimeruntime=Runtime.getRuntime();Stringcomando="C:\\Program Files\\Mozilla Firefox\\firefox.exe ";comando+=JOptionPane.showInputDialog("Digite a url");try{runtime.exec(comando);}catch(Exceptione){e.printStackTrace();}System.exit(0);}}
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
SidineiPJ
“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ó:
importjavax.swing.JOptionPane;publicclassTeste{publicstaticvoidmain(Stringargs[]){Runtimeruntime=Runtime.getRuntime();Stringcomando="C:\\Program Files\\Mozilla Firefox\\firefox.exe ";comando+=JOptionPane.showInputDialog("Digite a url");try{runtime.exec(comando);}catch(Exceptione){e.printStackTrace();}System.exit(0);}}
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
concianiPJ
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
EdersonPJ
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:
starthttp://www.portaljava.com
Um exemplo bem simples:
importjava.io.IOException;importjavax.swing.JOptionPane;publicclassCarregaURL{publicstaticvoidmain(String[]args){Stringcomando=JOptionPane.showInputDialog("Digite sua URL");try{Runtime.getRuntime().exec("start "+comando);}catch(IOExceptione){e.printStackTrace();}}}