Sandro
Sandro

Reputation: 2259

Is it possible to Hide Text through a Style?

I currently have a JTextPane that will be displaying text coming in from different streams. The way that the user can tell which stream the text came from is that the text from each stream has a different Style to it. Is there a way to make a Style that will hide the text so that I can filter out different pieces of text?

Thank you.

Upvotes: 1

Views: 679

Answers (1)

Mark Peters
Mark Peters

Reputation: 81124

You can (kind of) fake it by using a 0 font size and matching the background of the component:

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);
}

The length of the invisible string above doesn't even seem to have an affect on the space between the visible components. But rest assured it's still there, as copying from the pane will prove.

Upvotes: 2

Related Questions