Reputation: 79
I've created a custom border class where I fill a rectangle to act as a background for a component. Note that this border will have a more complex shape in the future, not just a simple rectangle.
When I add my border to a component, the text of the component will appear behind the border and make the text unreadable. (The result is depicted in the image below.)
Is there a way to draw the border below the text?
My border class:
public class CustomBorder extends AbstractBorder {
private static final long serialVersionUID = 1L;
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(125, 125, 125, 255));
g2d.fillRect(x - 10, y - 10, width + 20, height + 20);
}
@Override
public Insets getBorderInsets(Component c) {
return super.getBorderInsets(c);
}
@Override
public Insets getBorderInsets(Component c, Insets insets) {
return super.getBorderInsets(c, insets);
}
@Override
public boolean isBorderOpaque() {
return super.isBorderOpaque();
}
}
Main:
public static void main(String[] args) {
JLabel label = new JLabel("JLabel text");
label.setBorder(new CompoundBorder(new EmptyBorder(50, 20, 20, 20), new CustomBorder()));
JFrame frame = new JFrame("");
frame.setLayout(new FlowLayout());
frame.setSize(200, 200);
frame.add(label);
frame.setVisible(true);
}
Edit: I should also note that I will be using this border to a chat program, which will be using bubble-shaped messages, so a colored square using setBackground() is a no-no.
Upvotes: 1
Views: 563
Reputation: 324098
See A Closer Look at the Paint Mechanism which explains how the painting is done. The border is painted after the text of the label is painted.
What exactly are you trying to do? Your border painting code doesn't make sense. You are trying to fill a rectangle equal to the width/height of the component + 20 pixels, which means you are trying to paint an area larger than the component.
If you are just trying to paint a background on a label then you can use:
label.setOpaque( true );
label.setBackground(...);
Edit: The code in this answer that was linked in the comment section below solved the problem.
Upvotes: 3
Reputation: 703
You could always use g2d.drawString()
.
However, if that is not to be utilised for some reason, you could just do:
JLabel l = new JLabel("foo");
l.setBackground(Color.GRAY);
l.setOpaque(true);
Upvotes: 1