开发者

JMenu Help to Open Html page on local machine

I am having difficulty on fin开发者_如何学Goding a tutorial that enables a JMenuItem labelled ("Help Contents") to open a html page that displays help contents. The html page will be stored on the local machine eg C:\help. I have created the following action listener that when clicked, displays a string. This is only for test purposes to show that my ActionListener works.

   private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            JOptionPane.showMessageDialog(null, "Help File Popup");
        }

In summary, how would I replace:

JOptionPane.showMessageDialog(null, "Help File Popup");

So that when jMenuItem3 is pressed, an html page is loaded in the default browser. Many thanks in advance!


Quite easy when youre on Java 6:

take a look at this method

Desktop.browse("http://www.google.de/);

http://download.oracle.com/javase/6/docs/api/java/awt/Desktop.html#browse(java.net.URI)


If you want to open the default browser and display the html page you could use the jdic library. Or you can use a built-in swing component, JEditorPane that is able to display html, altough I'm not that sure if it renders it ok.

Here is a code (from swing tutorial):

JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
java.net.URL helpURL = TextSamplerDemo.class.getResource(
                            "TextSamplerDemoHelp.html");
if (helpURL != null) {
try {
    editorPane.setPage(helpURL);
} catch (IOException e) {
    System.err.println("Attempted to read a bad URL: " + helpURL);
}
} else {
System.err.println("Couldn't find file: TextSamplerDemoHelp.html");
}

//Put the editor pane in a scroll pane.
JScrollPane editorScrollPane = new JScrollPane(editorPane);
editorScrollPane.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
editorScrollPane.setPreferredSize(new Dimension(250, 145));
editorScrollPane.setMinimumSize(new Dimension(10, 10));

Using jdic, you can do something like this:

import org.jdesktop.jdic.browser.*;
Desktop.browse(new URL(inputUrl)); // open URL in   default browser


Have a look at java.awt.Desktop.


Thanks guys for all the help! For the action listener, I've currently implemented the following code:

public void actionPerformed(ActionEvent a) {
        // TODO add your handling code here:
        try{ 
            String url = "http://www.google.com"; 
            java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); 
          } 
          catch (java.io.IOException e) { 
              System.out.println(e.getMessage()); 
          } 
    }

Next thing to do is to create error messages if the default browser can not be selected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜