Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you open web pages in Java?

Tags:

java

web

jframe

Is there a simple way to open a web page within a GUI's JPanel?

If not, how do you open a web page with the computer's default web browser?

I am hoping for something that I can do with under 20 lines of code, and at most would need to create one class. No reason for 20 though, just hoping for little code...

I am planning to open a guide to go with a game. The guide is online and has multiple pages, but the pages link to each other, so I am hoping I only have to call one URL with my code.

like image 853
GA Tech Mike Avatar asked Apr 14 '09 18:04

GA Tech Mike


2 Answers

Opening a web page with the default web browser is easy:

java.awt.Desktop.getDesktop().browse(theURI);

Embedding a browser is not so easy. JEditorPane has some HTML ability (if I remember my limited Swing-knowledge correctly), but it's very limited and not suiteable for a general-purpose browser.

like image 112
Joachim Sauer Avatar answered Oct 16 '22 10:10

Joachim Sauer


There are two standard ways that I know of:

  1. The standard JEditorPane component
  2. Desktop.getDesktop().browse(URI) to open the user's default browser (Java 6 or later)

    Soon, there will also be a third:

  3. The JWebPane component, which apparently has not yet been released

JEditorPane is very bare-bones; it doesn't handle CSS or JavaScript, and you even have to handle hyperlinks yourself. But you can embed it into your application more seamlessly than launching FireFox would be.

Here's a sample of how to use hyperlinks (assuming your documents don't use frames):

// ... initialize myEditorPane
myEditorPane.setEditable(false); // to allow it to generate HyperlinkEvents
myEditorPane.addHyperlinkListener(new HyperlinkListener() {
    public void hyperlinkUpdate(HyperlinkEvent e) {
        if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) {
            myEditorPane.setToolTipText(e.getDescription());
        } else if (e.getEventType() == HyperlinkEvent.EventType.EXITED) {
            myEditorPane.setToolTipText(null);
        } else if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
            try {
                myEditorPane.setPage(e.getURL());
            } catch (IOException ex) {
                // handle error
                ex.printStackTrace();
            }
        }
    }
});
like image 2
Michael Myers Avatar answered Oct 16 '22 08:10

Michael Myers