简体   繁体   中英

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

I am learning Java and I have started to play with drawing possibilities.

Basically I have 2 questions:

  1. Why do I have to override paintCompoment method in order to paint something on JPanel ?
  2. Taking into account the first example when I call f.add(new MyPanel()); it creates a new MyPanel object and draw the text. How come the text is drawn? Method paintComponent(g) is not called.

To me it looks like 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 one: which works as well

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);

You are not supposed to call paintComponent() yourself.

The paintComponent() is called automatically (by the UI thread).

If you leave the paintComponent() method empty, it will be invoked but nothing will be painted because it is empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM