简体   繁体   English

JPanel绘图 - 为什么我必须覆盖paintComponent方法?

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

I am learning Java and I have started to play with drawing possibilities. 我正在学习Java,我已经开始玩绘画的可能性了。

Basically I have 2 questions: 基本上我有两个问题:

  1. Why do I have to override paintCompoment method in order to paint something on JPanel ? 为什么我必须覆盖paintCompoment方法才能在JPanel上绘制一些东西?
  2. Taking into account the first example when I call f.add(new MyPanel()); 考虑到我调用f.add(new MyPanel());时的第一个例子f.add(new MyPanel()); it creates a new MyPanel object and draw the text. 它创建一个新的MyPanel对象并绘制文本。 How come the text is drawn? 为什么要绘制文字? Method paintComponent(g) is not called. 方法paintComponent(g)未被调用。

To me it looks like I have two options: 对我来说,看起来我有两个选择:

First one (from http://docs.oracle.com/javase/tutorial/uiswing/painting/step2.html ): 第一个(来自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. 你不应该自己调用paintComponent()

The paintComponent() is called automatically (by the UI thread). paintComponent()被自动调用(由UI线程)。

If you leave the paintComponent() method empty, it will be invoked but nothing will be painted because it is empty. 如果将paintComponent()方法留空,则会调用它,但不会绘制任何内容,因为它是空的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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