问题
I am using an html page inside a swing JTextPane
in a JDialog.
In the html I have a <a href="mailto:email@adress.com">John</a>
When I view the web page via an explorer when the mouse goes to the link I can see the mailto
.
When I press the link I get the error "no default mail client installed", but I guess this is due to in my PC I have not configured Outlook or some other program.
When I open the JDialog from my Swing application, I see John
highlighted as a link, but when I press the link nothing happens.
I was expecting to get the same error message as the browser.
So my question is can the link be opened via a Swing application or not?
Thanks
回答1:
Neither the tooltip (showing the target hyperlink address) nor the action on press happens automatically, you have to code it: for the first, register the pane with the ToolTipManager, for the latter, register a HyperlinkListener, something like:
final JEditorPane pane = new JEditorPane("http://swingx.java.net");
pane.setEditable(false);
ToolTipManager.sharedInstance().registerComponent(pane);
HyperlinkListener l = new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if (HyperlinkEvent.EventType.ACTIVATED == e.getEventType()) {
try {
pane.setPage(e.getURL());
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
};
pane.addHyperlinkListener(l);
The example is about opening the page in the same pane. If you want to activate the default browser/mail-client, ask the Desktop (new to jdk1.6) to do it for you
回答2:
final JEditorPane jep = new JEditorPane("text/html",
"The rain in <a href='http://foo.com/'>Spain</a> falls mainly on the <a href='http://bar.com/'>plain</a>.");
jep.setEditable(false);
jep.setOpaque(false);
final Desktop desktop = Desktop.getDesktop();
jep.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent hle) {
if (HyperlinkEvent.EventType.ACTIVATED.equals(hle.getEventType())) {
try {
System.out.println(hle.getURL());
jep.setPage(hle.getURL());
try {
desktop.browse(new URI(hle.getURL().toString()));
} catch (URISyntaxException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
JPanel p = new JPanel();
p.add(new JLabel("Foo."));
p.add(jep);
p.add(new JLabel("Bar."));
JFrame f = new JFrame("HyperlinkListener");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(p, BorderLayout.CENTER);
f.setSize(400, 150);
f.setVisible(true);
来源:https://stackoverflow.com/questions/7291956/swing-jdialog-jtextpane-and-html-links