Search code examples
javaswingjframejpanelpaintcomponent

call paintcomponent for a jpanel in jframe


I have a JFrame with a JPanel on it (JPanel is private in JFrame). Now I want to override JPanel by using paintComponent method.

How can I do that?


Solution

  • When you create your instance of JPanel, (assuming you're doing it this way), do this:

    JPanel panel = new JPanel(){
        @Override
        public void paintComponent(Graphics g){
           // paint code
        }
    };
    

    The other alternative is to create a private class which extends JPanel.
    For example:

    public class OuterClass{
        // fields, constructors, methods etc..
    
        private class MyPanel extends JPanel{   
           // fields, constructors, methods etc..
    
           @Override
           public void paintComponent(Graphics g){
              // paint code
           }
    
        }
    }