1

我目前有一个 JTextPane 将显示来自不同流的文本。用户可以判断文本来自哪个流的方式是每个流中的文本具有不同的样式。有没有办法制作一个可以隐藏文本的样式,以便我可以过滤掉不同的文本?

谢谢你。

4

1 回答 1

2

您可以(有点)通过使用 0 字体大小并匹配组件的背景来伪造它:

public static void main(String[] args) throws Exception {
    JTextPane pane = new JTextPane();

    Style regular = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    Style invisible = pane.getStyledDocument().addStyle("invisible", regular);
    StyleConstants.setFontSize(invisible, 0);
    StyleConstants.setForeground(invisible, pane.getBackground());
    pane.getStyledDocument().insertString(pane.getStyledDocument().getLength(), 
            "Hello, ", null);
    pane.getStyledDocument().insertString(pane.getStyledDocument().getLength(), 
            "cruel ", pane.getStyledDocument().getStyle("invisible"));
    pane.getStyledDocument().insertString(pane.getStyledDocument().getLength(), 
            "world!", null);
    pane.setPreferredSize(new Dimension(500, 500));

    JFrame frame = new JFrame();
    frame.setLayout(new BorderLayout());
    frame.add(pane, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack(); frame.setVisible(true);
}

上面不可见字符串的长度甚至似乎对可见组件之间的空间没有影响。但请放心,它仍然存在,因为从窗格中复制将证明这一点。

于 2010-06-15T15:59:07.057 回答