I’m just playing with Swing and I’m working on a really simple Swing component. I have a component inherited from JComponent class and its UI inherited from ComponentUI. The paint() method looks like this:
public void paint(Graphics g, JComponent c) {
int x = c.getX();
int y = c.getY();
c.setBounds(x, y, 100, 25);
int width = c.getWidth();
int height = c.getHeight();
Rectangle r = g.getClipBounds();
g.fillRect(0, 0, 10, 10);
g.drawString("Baf!", 3, 3);
}
But it is totally impossible to get another value of r.height than 1. The component is width as given, but height allways one point only. Has anybody else experiences with suchlike components? Unfortunately there is no any easy tutorial. All tutorials are incomprehensible complicated (or obsolete).
It seems, that the layout manager resizes this component allways to 1 height (regardless to minimal value).
Never invoke setBound() in a painting method. That is a job for the layout manager, not your painting code.
I would guess the main problem (other than Heisenbug’s points) are that you don’t give you component a size. This is done by overriding the getPreferredSize() to return a size appropriate to your component.
Read the section from the Swing tutorial on Custom Painting for more information and working examples.