我有一个带有 StyledDocument“doc”的 JTextPane,我想在 doc.isertString(doc.getLength(), "http://www.google.com", attrs)
JTextPane 以显示可以单击的超链接。我以“http://www.google.com”和 attrs 为例,因为我真的不知道该怎么做。令人惊讶的是,我在网上找不到任何有用的东西(没有 html 或 HTMLDocument 等)。我不喜欢 swing 如何与 html 一起工作,我不想使用它。
public class SSCCE extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SSCCE frame = new SSCCE();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SSCCE() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
StyledDocument doc = textPane.getStyledDocument();
SimpleAttributeSet attrs = new SimpleAttributeSet();
try {
doc.insertString(doc.getLength(), "http://www.google.com", attrs);
} catch (BadLocationException e) {
e.printStackTrace();
}
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(textPane, GroupLayout.PREFERRED_SIZE, 422, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(textPane, GroupLayout.PREFERRED_SIZE, 248, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
contentPane.setLayout(gl_contentPane);
}
}
最佳答案
定义您自己的 AttributeSet
以保留超链接信息。它应该包括例如蓝色和自定义属性。我们将其命名为“URL”。使用 AttributeSet
添加一些文本到 StyledDocument
。
然后添加一个鼠标监听器(Motion and mouse listener)。对于任何鼠标事件,您都可以使用 viewToModel()
获取指定鼠标位置的偏移量。获取偏移量的叶元素(文本)并检查文本 Element
是否具有属性。
如果它执行了您的操作(例如,将鼠标光标设置为手或处理点击 URL)。
关于java - 如何在没有 html 的情况下向 JTextPane 添加超链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14038703/