java如何在工具栏窗格中显示可单击的链接
我正试图在JEditorPane中显示可单击链接的列表。 这是我的密码:
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Style;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
public class GUI extends JFrame{
JEditorPane editorpane=new JEditorPane();
//this is the constructor
GUI(){
JFrame frame=new JFrame("Frame");
frame.add(editorpane);
JScrollPane scroll=new JScrollPane(editorpane);
editorpane.setContentType("text/html");
editorpane.setEditable(false);
editorpane.setText("<html><body>Test <a href='http://www.java.net'>"
+ "www.java.net</a></body></html>");
StyleSheet css = ((HTMLEditorKit)
editorpane.getEditorKit()).getStyleSheet();
Style style = css.getStyle("body");
editorpane.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() ==
HyperlinkEvent.EventType.ACTIVATED) {
System.out.println("Open browser: " + e.getURL());
}
}
});
frame.setSize(512, 342);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scroll);
frame.show();
}
public void append(String s) {
try{
Document doc = editorpane.getDocument();
doc.insertString(doc.getLength(), "\n", null);
doc.insertString(doc.getLength(), s, null);
}
catch(BadLocationException exc){
}
}
//main method
public static void main(String args[]){
GUI gui=new GUI();
gui.append("<html><body>Test <a href='http://www.java.net'>"
+ "www.java.net</a></body></html>");
}
}
当我在构造函数中使用setText()方法时,它显示了一个可单击的链接,但当我试图用append()显示其他链接时;方法它显示html标记和文本,并且不会使我的url成为超链接。任何想法,为什么它不与append一起工作
# 1 楼答案
使用HTMLEditorKit的任一方法
或HTMLDocument的方法