Graph
对象正被添加到JFrame
。此对象绘制轴,然后绘制图形图。当使用:{/ p>通过paint()
隐式调用对象的JFrame
时
this.getContentPane().add(new Graph());
轴和功能绘制。但是,当显式调用paint()
方法时,通过:
Graph g = new Graph();
g.paint(this.getContentPane().getGraphics());
轴不绘制,但功能确实如此。 JFrame
的完整构造函数如下:
public GraphFrame() {
super("");
setSize(800, 800);
setVisible(true);
//One of the above blocks is called here
}
对象paint
中的函数Graph
如下:
public void paint(Graphics w) {
w.setColor(Color.WHITE);
w.fillRect(0, 0, 800, 800); //Clears the screen
w.setColor(Color.BLACK);
w.drawLine(100, 0, 100, 800);
w.drawLine(0, 700, 800, 700); //(Should) Draw the axes
for(int i = 1; i < 650; i++) {
//Draws the function
//This is just a repeated drawLine call.
}
}
为什么在组件绘制时隐式调用轴时绘制轴,但在显式调用时不绘制?请记住,函数绘制(for
循环中的块),而for循环前面的轴则没有。
答案 0 :(得分:2)
不要直接在组件上调用paint
。另外,对于Swing中的自定义绘画,请使用paintComponent
而不是paint
,并记得致电super.paintComponent(g)
。此外,getGraphics
会返回临时Graphics
引用,因此不应将其用于自定义绘制。相比之下,Graphics
(和paint
)中的paintComponent
引用始终会正确初始化,并会按预期显示图形输出。