How can we implement the paintComponent() method of a JPanel in Java?


A JPanel is a lightweight container and it is an invisible component in Java. A JPanel's default layout is FlowLayout. After the JPanel has been created, other components can be added to the JPanel object by calling its add() method inherited from the Container class.

paintComponent()

This method is needed to draw something on JPanel other than drawing the background color. This method already exists in a JPanel class so that we need to use the super declaration to add something to this method and takes Graphics objects as parameters. The super.paintComponent() which represents the normal the paintComponent() method of the JPanel which can only handle the background of the panel must be called in the first line.

Syntax

protected void paintComponent(Graphics g)

Example

import java.awt.*;
import javax.swing.*;
public class SmileyApp extends JPanel {
   @Override
   public void paintComponent(Graphics g) {
      super.paintComponent(g);
      g.setColor(Color.YELLOW);
      g.fillOval(10, 10, 200, 200);
      // draw Eyes
      g.setColor(Color.BLACK);
      g.fillOval(55, 65, 30, 30);
      g.fillOval(135, 65, 30, 30);
      // draw Mouth
      g.fillOval(50, 110, 120, 60);
      // adding smile
      g.setColor(Color.YELLOW);
      g.fillRect(50, 110, 120, 30);
      g.fillOval(50, 120, 120, 40);
   }
   public static void main(String[] args) {
      SmileyApp smiley = new SmileyApp();
      JFrame app = new JFrame("Smiley App");
      app.add(smiley, BorderLayout.CENTER);
      app.setSize(300, 300);
      app.setLocationRelativeTo(null);
      app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      app.setVisible(true);
   }
}

Output

Updated on: 07-Feb-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements