显示两个图像而不是一个

时间:2014-08-26 15:08:10

标签: java swing jtextpane

我想在JTextPane的开头添加一个图像。我原来用过:

textPane.insertIcon(new ImageIcon("icon");

但这根本没有做任何事情,至少在我更改文档后使用了文本窗格。

所以我用的是样式。这是我使用的代码:

public QuotePanel(String quoted, DefaultStyledDocument quoteText) throws BadLocationException {
        initComponents(); //Netbeans GUI builder, should be irrevelant

        quotePane.setStyledDocument(quoteText); //QuotePane is a JTextPane declared as a global variable.
        Style icon = quoteText.addStyle("Quote Icon", null);
        ImageIcon quoteIcon = new ImageIcon(this.getClass().getResource("/images/posts/quotes.png"));
        StyleConstants.setIcon(icon, quoteIcon);
        quoteText.insertString(0, "Quotation Icon", icon);
        quoteText.insertString(1, (quoted + " said: " + "\n\n"), null);
}

这很有效,但它有一些有趣的副作用。然后,这是我用来测试TextPane的主要方法:

public static void main(String args[]) {
        QuotePanel quote = null;

        try {
            DefaultStyledDocument test = new DefaultStyledDocument();
            test.insertString(0, "This is a test\n\n", null);
            JTextPane pane = new JTextPane();
            Style styleRed = pane.addStyle("Red", null);
            StyleConstants.setForeground(styleRed, Color.red);
            test.insertString(test.getLength() - 1, "This is red\n", styleRed);
            Style styleBold = pane.addStyle("Bold", null);
            StyleConstants.setBold(styleBold, true);
            test.insertString(test.getLength() - 1, "This is Bold\n", styleBold);
            Style styleSmall = pane.addStyle("Small", null);
            StyleConstants.setFontSize(styleSmall, 8);
            test.insertString(test.getLength() - 1, "This is small\n", styleSmall);


            quote = new QuotePanel("Quoted Person", test);

        } catch (Exception e) {
            System.out.println("Oops, got an exception.");
            e.printStackTrace();
            System.exit(1);
        }
       JFrame frame = new JFrame("test");

       frame.add(quote);
       quote.setVisible(true);
       frame.setSize(467, 126);
       frame.validate();
       frame.setVisible(true);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

我得到的输出是:

enter image description here

为什么引号出现两次?我只在代码中出现一次。 (或者至少我只有一行添加它们)。我确实研究了为什么会这样,但我在其他任何地方都找不到这个问题。据我所知,在SO上没有关于这个问题的信息。

1 个答案:

答案 0 :(得分:0)

好的,我没有弄清楚确切的答案,但我确实想出了如何将单个图像添加到JTextPane。

我的第一段代码是在正确的轨道上:

textPane.insertIcon(new ImageIcon("icon");

我需要知道的是insertIcon()方法实际上将图像放在选择的位置。因此,为了正确放置图标,我需要选择我想放在首位的地方。

所以我使用了这段代码:

quotePane.select(0, 0);
quotePane.insertIcon(quoteIcon);

这产生了正确的输出,在JTextPane的开头只有一个图标。

相关问题