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

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

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)调用实际函数?!

4

2 回答 2

5

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

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

无论如何,当你在屏幕上绘画时,你永远不应该调用paint/paintComponent/paintXXX 方法。只能打电话repaint()

您不能依赖“何时”调用您的方法 paintComponent(Graphics) 或 paint(Graphics)。

于 2012-10-12T14:57:52.983 回答
4

paint在需要时由 Swing 自动调用,例如当组件变为可见时(第一次,或在窗口最小化后等),或当窗口调整大小时,基本上每当组件的内容需要时被画。你永远不应该paint在你的代码中显式调用,如果你想强制paint那么你应该调用repaint

链接可能会有所帮助

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

于 2012-10-12T14:51:08.010 回答