2014-03-31 71 views
1

如何在JTextPane上創建超鏈接。下面的代碼使用getStyleDdocument的超鏈接不起作用

import java.awt.BorderLayout; 
import java.awt.EventQueue; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.border.EmptyBorder; 
import javax.swing.text.BadLocationException; 
import javax.swing.text.StyledDocument; 
import javax.swing.JLabel; 
import javax.swing.BoxLayout; 
import javax.swing.JScrollPane; 
import javax.swing.JTextField; 
import javax.swing.JCheckBox; 
import javax.swing.JButton; 
import javax.swing.JTextPane; 

public class Sample extends JFrame { 

    private JPanel contentPane; 
    private JTextField textField; 
    private JTextField textField_1; 

    /** 
    * Launch the application. 
    */ 
    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        Sample frame = new Sample(); 
        frame.setVisible(true); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    /** 
    * Create the frame. 
    * @throws BadLocationException 
    */ 
    public Sample() throws BadLocationException { 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setBounds(100, 100, 450, 300); 
     contentPane = new JPanel(); 
     contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
     contentPane.setLayout(new BorderLayout(0, 0)); 
     setContentPane(contentPane); 

     JPanel panel = new JPanel(); 
     contentPane.add(panel, BorderLayout.NORTH); 

     JLabel lblNewLabel = new JLabel("New label"); 
     panel.add(lblNewLabel); 

     JTextPane textPane = new JTextPane(); 
     JScrollPane pane = new JScrollPane(textPane); 
     contentPane.add(pane, BorderLayout.CENTER); 

     textPane.setContentType("text/html"); 
     textPane.setEditable(false); 

     StyledDocument doc = textPane.getStyledDocument(); 
     doc.insertString(doc.getLength(), "Hello\n", null); 
     doc.insertString(doc.getLength(), "<a href=\"\">Cancel</a>\n", null); 

    } 

} 

回答

3

閱讀JEditorPane API對於如何將HyperlinkListener添加到一個JEditorPane或JTextPane的一個例子。

編輯:

我真的不明白操作HTML,但我認爲有以下應該工作:

HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit(); 
HTMLDocument doc = (HTMLDocument)textPane.getDocument(); 
String text = "<a href=\"abc\">hyperlink</a>"; 
editorKit.insertHTML(doc, doc.getLength(), text, 0, 0, null); 
+0

這是不是'HyperLinkListener'。當您嘗試運行該程序時,我會看到html標記而不是超鏈接。 – Mercenary

+0

@Mercenary:提出了一些替代方案[這裏](http://stackoverflow.com/a/16447176/230513)。 – trashgod

+0

@Mercenary,你真的應該使用JEditorPane來顯示HTML。 API有一個Swing教程的鏈接。請參閱編輯一些代碼以動態添加文本。 – camickr