Re: Custom JPanel that clips children?



Arabella <AZ@xxxxxxxx> wrote:

> I'm trying to implement a JPanel with rounded corners that clips it's
> children so they don't run outside the jpanel's (now rounded) corners.
>
> I'm able to clip the JPanel, but the children keep painting outside the
> jpanel parent.
>
> Do I have to override the paint routines of every child, or is there a way
> for a parent to clip children?

1. clipping in paintChildren.
2. making sure paintChildren is called on the panel and the children are
not painted directly. In principle, there is a way to do (JComponent.isPaint
Origin), but this is package-private. The hack to do it anyway is to
- override isOptimizedDrawingEnabled to return false
- add a bogus component on top that covers every other child (at least
partially?)
This may affect paint performance, but probably not too much.

Try this: (a) clips children, (b) paint on top of the children.

import javax.swing.*;

import java.awt.*;


public class POC
extends JComponent
{
public POC()
{
add(new JComponent() { });
add(new JTextField("XXX 2301923 91283 ")
{
public boolean isValidateRoot()
{
return false;
}
});
}


public void doLayout()
{
getComponent(0).setBounds(0, 0, getWidth(), getHeight());

Dimension d = getComponent(1).getPreferredSize();

getComponent(1).setBounds(10, 10, d.width, d.height);
}

public Dimension getPreferredSize()
{
return new Dimension(400, 400);
}

public boolean isOptimizedDrawingEnabled()
{
return false;
}

protected void paintChildren(Graphics g)
{
Shape s = g.getClip();

{
g.clipRect(20, 20, getWidth() - 40, getHeight() - 40);
}
try
{
super.paintChildren(g);
}
finally
{
g.setClip(s);
}

g.setColor(Color.red);

Rectangle r = getComponent(1).getBounds();

g.fillRect(r.x + r.width / 2, r.y, r.width / 2, r.height / 2);
}


public static void main(String[] args)
{
POC p = new POC();

JFrame f = new JFrame();

f.getContentPane().add(p);

f.pack(); f.show();
}
}



Christian
.