I'm trying to make a border with round corners. Inside the borders should be anything that the component, for which the border is set, decides to draw, and outside the borders should "nothing"; that is, it should draw the parent component's paint in those places.
What I'm trying to get:
What I'm getting:
See the white corners of the container with blue borders. I need to get rid of them. I'm trying to achieve this with a custom Border
:
public class RoundedLineBorder extends AbstractBorder {
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Graphics2D g2 = (Graphics2D) g;
int arc = 20;
RoundRectangle2D borderRect = new RoundRectangle2D.Double(
0, 0, width - 1, height - 1, arc, arc);
Rectangle fullRect = new Rectangle(
0, 0, width, height);
Area borderArea = new Area(borderRect);
Area parentArea = new Area(fullRect);
parentArea.subtract(borderArea);
Component parent = c.getParent();
if (parent != null) {
g2.setColor(parent.getBackground());
/* fill parent background color outside borders */
g2.setClip(parentArea);
g2.fillRect(fullRect);
g2.setClip(null);
}
g2.setColor(Color.blue);
/* draw borders */
g2.draw(borderArea);
}
}
This works fine when the parent component has a solid background, but if it has a background image it of course doesn't. Is there a way of getting the actual colours that are painted under the aforementioned places?
Is there a better way of achieving rounded borders without actually extending a JPanel
and just doing it all in its paintComponent
?