Home > database >  Paint and PaintComponent Methods in JPanel
Paint and PaintComponent Methods in JPanel

Time:12-23

I am having trouble in understanding the difference between the paint and the paintComponent methods defined in the JPanel class. To put you in context, I am trying to draw a chess table; the following is part of the code I have been working on.

package main;

import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Color;

public class Panell extends JPanel {
    
    public Panell() {

    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawRect(100, 100, 400, 400);
    }

    @Override
    public void paint(Graphics g){
        boolean white=true;
        for(int y=0;y<8;y  ){
            for(int x=0;x<8;x  ){
                if(white){
                    g.setColor(new Color(235, 235, 208));
                }
                else{
                    g.setColor(new Color(119, 148, 85));
                }
                g.fillRect(x*15, y*15, 15, 15);
                white=!white;
            }
            white=!white;
        }
    }
}

One of my first questions is Are they runned automatically? Also, since they apparently do the same thing, which is to "paint", is it recommended to merge this two methods in one? Which would be the name of this one method?

I'm pretty new to Java and so any help will be very much appeciated. Thanks!

I have been following multiple tutorials online but any of them mentioned my question. I suppose it might be a really indepth topic, but I would really like to know the answer. I have tried everything that I have said in the question and I always end up painting one thing over the other, hence I asked myself if it would be better to only have one single paint method (by merging them), but by doing that, another question arises, Why would they implement another method to do exacly the same as another method?.

CodePudding user response:

Are they runned automatically?

No. They are actually called by the windowing system when the Component needs to be repainted (i.e. first shown, resized, user calls repaint())

Also, since they apparently do the same thing, which is to "paint", is it recommended to merge this two methods in one?

The difference between paint and paintComponent is that in Swing, JComponent implements paint to call paintBorder, paintChildren, and paintComponent in the proper (expected) order. So normally if you are subclassing a J-whatever in Swing, it is better to override paintComponent, not paint

  • Related