正在向JFrame
添加Graph
对象。该对象绘制轴,然后是图形图。当对象的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
}
对象Graph
中的paint
函数如下:
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循环之前的轴不会。
不要在组件上直接调用paint
。对于Swing中的自定义绘画,请使用paintComponent
而不是paint
,并记住调用super.paintComponent(g)
。此外,getGraphics
返回一个瞬态Graphics
引用,所以不应该用于自定义绘画。相比之下,paint
(和paintComponent
)中的Graphics
引用总是被正确初始化,并将按预期显示图形输出。
- 执行自定义绘画
- 在AWT和Swing中绘画