Is it possible to call repaint() inside the main()?I have tried the code below.But its not working

 public mypanel() 
            {
                initComponents();
                repaint(100,150,40,40);        
            }
             protected void paintComponent(final Graphics g) 
             {     
                final Graphics2D g2 = (Graphics2D)jLabel2.getGraphics();       
                g2.drawRect(100,150,40,40);       
            }
            //above code doesnt provide any output
            private void formMouseClicked(java.awt.event.MouseEvent evt)
           {  
           repaint(100,150,40,40)
           }


this code  draws the rectangle.But I want to draw it when the program execution starts.Please help to solve this(rect

angle drawn on an image placed in jLabel).

The problem is probably in the code you didn't post!

Eg: If you don't set a size and/or minimum size for your mypanel then the layout manager for its parent will look at mypanel's children (none) and decide that 0x0 pixels is a big enough size for it.

final Graphics2D g2 = (Graphics2D)jLabel2.getGraphics();
No. You MUST draw to the Graphics you wre passed
final Graphics2D g2 = (Graphics2D) g;
Swing is double-buffered, and if you just draw to some random Graphics it will almost certainly be ignored and/or overwritten by the buffering.

ps Java naming conventions: MyPanel, not mypanel for a class name
add @Override annotations to your paintComponent/actionPerformed etc so the compiler will pick up any mis-spelling in your method signatures -this prevents a very commion class of problem where nothing happens because the methods didn't override properly.

This article has been dead for over six months. Start a new discussion instead.