Tôi đang cố hiển thị danh sách các liên kết có thể nhấp trong JEditorPane. Đây là mã của tôi:cách hiển thị các liên kết có thể nhấp trong 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>");
}
}
Nó được hiển thị liên kết có thể click, khi tôi sử dụng phương pháp trong các nhà xây dựng setText(), nhưng sau đó khi tôi đã cố gắng để hiển thị liên kết bổ sung với append(); phương pháp nó được hiển thị các thẻ html cùng với các văn bản và nó không làm cho url của tôi một siêu liên kết. Bất kỳ ý tưởng nào, tại sao nó không hoạt động với phụ thêm?
Thanks a lot Stanislav !! Tôi quản lý để có được nó làm việc :) Tôi tìm thấy một trong những ý kiến của bạn trên một bài tương tự và cả hai đã giúp tôi sắp xếp ra vấn đề của tôi. – curious