2014-03-31 38 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