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 t开发者_如何学编程utorials 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.
There are several problems with your code:
For what concern the class extending JComponent:
public void paint(Graphics g, JComponent c) {}
isn't a valid signature so you are not overriding the method paint, but create a new paint method.
you should override paintComponent(Graphics g) method instead of paint.
Because of you are extending a JComponent you need first call super.paintComponent(g) inside your overridden paintComponent method:
public class JPanelExtended{ public void paintComponent(Graphics g){ super.paintComponent(g); ... } }
For what concern the class extending ComponentUI, you should even there call explicitly the method paint on the super class:
public void paint(Graphics g, JComponent c) {
super.paint(g,c);
}
EDIT: a little suggestion: when you want to override a method, it's quite useful to put the @override notation before the signature:
@Override
public void superMethodToBeOverridden(){}
This way you will be notified by the compiler with an error message, in the case you are defining a new method and not overriding an existing one.
精彩评论