paint(Graphics g)函数被调用但我不知道在哪里?

时间:2012-10-12 14:28:42

标签: java swing

package donut;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;

import javax.swing.JPanel;


public class Board extends JPanel{

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

      Graphics2D g2 = (Graphics2D) g;

      RenderingHints rh =
            new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                               RenderingHints.VALUE_ANTIALIAS_ON);

      rh.put(RenderingHints.KEY_RENDERING,
             RenderingHints.VALUE_RENDER_QUALITY);

      g2.setRenderingHints(rh);

      Dimension size = getSize();
      double w = size.getWidth();
      double h = size.getHeight();

      Ellipse2D e = new Ellipse2D.Double(0, 0, 80, 130);
      g2.setStroke(new BasicStroke(1));
      g2.setColor(Color.gray);


      for (double deg = 0; deg < 360; deg += 5) {
          AffineTransform at =
              AffineTransform.getTranslateInstance(w / 2, h / 2);
          at.rotate(Math.toRadians(deg));
          g2.draw(at.createTransformedShape(e));
        }
    }
}

然后JFrame扩展类 Board 对象被实例化

package donut;

import javax.swing.JFrame;


public class Donut extends JFrame {


    public Donut() {

        add(new Board());

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(360, 310);
        setLocationRelativeTo(null);
        setTitle("Donut");
        setVisible(true);
    }

    public static void main(String[] args) {
        new Donut();
    }
}

我期待看到像这样的行:new Board().paint(graphicsObject)那么实际上这行是执行还是以适当的方式实际调用了paint(Graphics g)函数?!

2 个答案:

答案 0 :(得分:5)

如果你想跟随调用堆栈绘制(),只需编写new Throwable().printStackTrace()Thread.dumpStack(),这将允许你跟随调用堆栈。

否则,请查看RepaintManager.addDirtyRegion(JComponent, int, int, int, int);

无论如何,当你画到屏幕上时,你永远不应该调用paint / paintComponent / paintXXX方法。只需致电repaint()

你不能依赖“when”你的方法将调用paintComponent(Graphics)或paint(Graphics)。

答案 1 :(得分:4)

无论什么时候需要,都会自动调用

paint,例如当组件变得可见时(第一次,或者在最小化窗口之后等),或者窗口调整大小时,基本上每当需要绘制组件的内容时。您不应该在代码中明确调用paint,如果您想强制paint,那么您应该拨打repaint

link可能会有所帮助

P.S。由paint调用的super.paint(g)方法的代码驻留在JComponent类中,该类由JPanel扩展(由Board类扩展)。