控制JTextPane上的图像放置

时间:2015-09-02 05:04:29

标签: jtextpane imageicon

我能够将ImageIcons添加到JTextPane,但是当我添加它们时,它们会显示在JTextPane的中心。我找不到一种方法来控制它们放在JTextPane上的位置。有人可以帮帮我吗?

此方法正在制作JTextPane:

private void loadTextPanel(JPanel contentPane) {
    chatLogPanel = new JPanel();
    chatLogPanel.setLayout(null);
    EmptyBorder eb = new EmptyBorder(new Insets(10, 10, 10, 10));

    DefaultStyledDocument document = new DefaultStyledDocument();
    chatLog = new JTextPane(document);
    chatLog.setEditorKit(new WrapEditorKit());
    chatLog.setBorder(eb);
    chatLog.setMargin(new Insets(5, 5, 5, 5));
    chatLogScrollPane = new JScrollPane(chatLog);

    addComponent(chatLogPanel, chatLogScrollPane, 0, 0, 500, 240);
    addComponent(contentPane, chatLogPanel, 0, 40, 500, 240);
}

这是我用来向Panel添加字符串的代码:

private static void appendToChatLog(JTextPane tp, String msg, Color c) {
    chatLog.setEditable(true);
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

    aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
    aset = sc.addAttribute(aset, StyleConstants.Alignment, Integer.valueOf(3));

    int len = tp.getDocument().getLength();
    tp.setCaretPosition(len);
    tp.setCharacterAttributes(aset, false);
    tp.replaceSelection(msg);
    chatLog.setEditable(false);
}

这就是我目前用于将图像添加到JTextPane的内容:

BufferedImage image = generateBufferedImage(message.getImage());
Icon icon = new ImageIcon(image);

StyleContext context = new StyleContext();
StyledDocument document = (StyledDocument) chatLog.getDocument();

Style labelStyle = context.getStyle(StyleContext.DEFAULT_STYLE);

JLabel label = new JLabel(icon);
StyleConstants.setComponent(labelStyle, label);

try {
    document.insertString(document.getLength(), "Ignored", labelStyle);
} catch (BadLocationException badLocationException) {
    badLocationException.printStackTrace();
}

1 个答案:

答案 0 :(得分:0)

要将组件插入JTextPane,并将其显示为字符,请使用insertComponent方法。

要插入图标,请使用insertIcon方法。

相当直观不是;)