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.
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.
精彩评论