The Java paint() Method

This is a very simple example of Java’s paint() method. The paint() method takes an instance of the Graphics class. The Graphics class contain methods which are used for graphics operations. The following code paint a blue rectangle onto a JPanel component.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Paint extends JPanel {

   public static void main(String[] a) {
      JFrame f = new JFrame();
      f.setSize(400, 400);
      Paint p = new Paint();
      f.add(p);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setVisible(true);
   }
   @Override
   public void paint(Graphics g) {
       g.setColor(Color.blue);
       g.fillRect (5, 15, 50, 75);
     
   }
}

Leave a Reply