JPanel drawing - why do I need to override paintComponent method?

I am learning Java and I started playing with drawing capabilities.

Basically I have 2 questions:

  • Why do I need to override the method paintCompoment

    to draw something on JPanel

    ?
  • Keeping in mind the first example, when I call f.add(new MyPanel());

    it creates a new object MyPanel

    and draws the text. How will the text come out? The method is paintComponent(g)

    not called.

It seems to me that I have two options:

First one (from http://docs.oracle.com/javase/tutorial/uiswing/painting/step2.html ):

package painting;

import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

public class SwingPaintDemo2 {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI(); 
            }
        });
    }

    private static void createAndShowGUI() {
        System.out.println("Created GUI on EDT? "+
        SwingUtilities.isEventDispatchThread());
        JFrame f = new JFrame("Swing Paint Demo");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new MyPanel());
        f.pack();
        f.setVisible(true);
    }
}

class MyPanel extends JPanel {

    public MyPanel() {
        setBorder(BorderFactory.createLineBorder(Color.black));
    }

    public Dimension getPreferredSize() {
        return new Dimension(250,200);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);       

        // Draw Text
        g.drawString("This is my custom Panel!",10,20);
    }  
}

      

Second: which works also

Graphics g = panel.getGraphics();
g.setColor(new Color(255, 0, 0));
g.drawString("Hello", 200, 200);
g.draw3DRect(10, 20, 50, 15, true);
panel.paintComponents(g);

      

+3


source to share


1 answer


You don't have to name it yourself paintComponent()

.

paintComponent()

called automatically (on the UI thread).



If you leave the method paintComponent()

empty, it will be called, but nothing will be colored because it is empty.

+2


source







All Articles