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)
函数?!
答案 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
类扩展)。