Tagged “swing”

Java: Howto embed SWT widget into Swing JFrame

Published by cybso on

This is a post from my original site, which was hosted by the former blog service of the University of Osnabrück. I have moved it to the new site for archiving. Pages linked in this article may no longer work today, and the blog comments under the article no longer exist. Opinions expressed in this article reflect the point of view of the time of publication and do not necessarily reflect my opinion today.

Today I wanted to embed a SWT component (Browser) into an existing JFrame. This is the way it works:

(continue reading)

JTextPane with background color

Published by cybso on

This is a post from my original site, which was hosted by the former blog service of the University of Osnabrück. I have moved it to the new site for archiving. Pages linked in this article may no longer work today, and the blog comments under the article no longer exist. Opinions expressed in this article reflect the point of view of the time of publication and do not necessarily reflect my opinion today.

JTextPane and his ancestors JEditorPane and JTextComponent won't respect the color defined with setBackground(Color) since they display a "styled document" and expect the background color to be defined in the content. You'll always see a white background.

To change the background color (without modifying the content) you have to define attributes for the document:

JTextPane textPane = new JTextPane();
textPane.setContentType("text/html"); // or any other styled content type
textPane.setText("White text on a red background");

textPane.setForeground(Color.white); // Works as expected
textPane.setBackground(Color.red); // Obsolete, no affect

// Define a default background color attribute
Color backgroundColor = Color.red;
SimpleAttributeSet background = new SimpleAttributeSet();
StyleConstants.setBackground(background, backgroundColor);
textPane.getStyledDocument().setParagraphAttributes(0,
        textPane.getDocument().getLength(), background, false);

// And remove default (white) margin
textPane.setBorder(BorderFactory.createEmptyBorder());

// Alternative: Leave a 2px border but draw it in the same color
textPane.setBorder(BorderFactory.createLineBorder(backgroundColor, 2));