我有一个带有StyledDocument“doc”的JTextPane,当我想要JTextPane显示一个可以单击的超链接时。我把“http://www.google.com”和attrs作为例子,因为我真的不知道如何去做。令人惊讶的是,我找不到任何有用的信息(没有html或HTMLDocument等)。我不喜欢swing如何处理html,我不喜欢使用它。如何将超链接添加到没有html的JTextPane?
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);
}
}