Search code examples
graphicsnulljlabelclip

Before setting JLabel's Clip with a shape (polygon) getClip() still return null


In my program I try to set the Clip of a JLabel like this:

JLabel  jl = new JLabel();
jl.setVisible(true);
jl.setSize( 50, 50);
componentWhereIPutEverything.add( jl);
jl.setLocation( 50 , 50);

int xx[] = { (int) UpLeft.getX(), (int) UpRigth.getX(), (int) BottomRigth.getX(), (int) BottomLeft.getX()   };
int yy[] = { (int) UpLeft.getY(), (int) UpRigth.getY(), (int) BottomRigth.getY(), (int)  BottomLeft.getY()  };
Polygon poly = new Polygon(xx, yy, xx.length);
jlabel.getGraphics().setClip( poly );

After this, i try:

jl.getGraphics().getClip()

and it returns null. How can I fix it? Where are the errors? Thanks ;)


Solution

  • Just because you set the clip on one graphics object doesn't mean that it will be there for all graphics objects. Your best solution is to override getGraphics() and add your setClip in there

    public Graphics getGraphics() { Graphics g = super.getGraphics(); g.setClip(...); return g; }