使用getStyleDdocument的超链接不起作用

时间:2014-03-31 15:09:38

标签: java html swing hyperlink jtextpane

如何在JTextPane上创建超链接。代码

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);

    }

}

1 个答案:

答案 0 :(得分: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);