Pregunta

I am trying to make a close button in an undecorated JFrame. I have made a Polygon

Polygon closePol = new Polygon(
            new int[] {getWidth() - 25, getWidth(), getWidth(), getWidth() - 25}, 
            new int[] {0, 0, 25, 25}, 4);

When I do this, g.fillPolygon(closePol); nothing happens but when I do this

g.fillPolygon(new int[] {getWidth() - 25, getWidth(), getWidth(), getWidth() - 25}, 
              new int[] {0, 0, 25, 25}, 4);` , 

I see a polygon. Why isn't the first one working?

¿Fue útil?

Solución

The problem is likely that getWidth() in closePol is called outside the scope of the paintComponent method, so the current width is is not yet taken into account (or may still be zero), which could happen due a a few reasons.

As a general rule, when painting, you will want to call getWidth()/getHeight() in the paint[Component]() method. For example when expanding the frame, if getWidth() is not called with the method, the new width will not be taken into account, and there will be no dynamic resizing of the graphic (if that's what you want.

You will also want to consider overriding getPreferredSize() when doing custom painting, as to give the panel some sizing hints.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top