Paint() 是如何在没有在 main 方法中调用的情况下运行的?
这是使用 awt 包的 java 图形的初学者问题。我在网上找到了这段代码来绘制一些简单的图形。
import java.awt.*;
public class SimpleGraphics extends Canvas{
/**
* @param args
*/
public static void main(String[] args) {
SimpleGraphics c = new SimpleGraphics();
c.setBackground(Color.white);
c.setSize(250, 250);
Frame f = new Frame();
f.add(c);
f.setLayout(new FlowLayout());
f.setSize(350,350);
f.setVisible(true);
}
public void paint(Graphics g){
g.setColor(Color.blue);
g.drawLine(30, 30, 80, 80);
g.drawRect(20, 150, 100, 100);
g.fillRect(20, 150, 100, 100);
g.fillOval(150, 20, 100, 100);
}
}
main 方法中没有在画布上调用 Paint() 。但是我运行了程序并且它可以工作,那么paint()方法是如何运行的呢?
This is a beginner question for java graphics using the awt package. I found this code on the web to draw some simple graphics.
import java.awt.*;
public class SimpleGraphics extends Canvas{
/**
* @param args
*/
public static void main(String[] args) {
SimpleGraphics c = new SimpleGraphics();
c.setBackground(Color.white);
c.setSize(250, 250);
Frame f = new Frame();
f.add(c);
f.setLayout(new FlowLayout());
f.setSize(350,350);
f.setVisible(true);
}
public void paint(Graphics g){
g.setColor(Color.blue);
g.drawLine(30, 30, 80, 80);
g.drawRect(20, 150, 100, 100);
g.fillRect(20, 150, 100, 100);
g.fillOval(150, 20, 100, 100);
}
}
Nowhere in the main method is paint() being called on the canvas. But I ran the program and it works, so how is the paint() method being run?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
paint
方法由事件调度线程 (EDT) 调用,基本上不受您的控制。它的工作原理如下:当您实现一个用户界面(在您的情况下调用
setVisible(true)
)时,Swing 启动 EDT。然后,此 EDT 线程在后台运行,每当您的组件需要绘制时,它都会使用适当的Graphics
实例调用paint
方法,供您用于绘制。那么,什么时候组件“需要”重新绘制呢? -- 例如,当
repaint
时只需假设只要有必要,它就会被调用。
The
paint
method is called by the Event Dispatch Thread (EDT) and is basically out of your control.It works as follows: When you realize a user interface (call
setVisible(true)
in your case), Swing starts the EDT. This EDT thread then runs in the background and, whenever your component needs to be painted, it calls thepaint
method with an appropriateGraphics
instance for you to use for painting.So, when is a component "needed" to be repainted? -- For instance when
repaint
Simply assume that it will be called, whenever it is necessary.
实际上你自己从来没有调用过绘制方法。每当框架的内容窗格需要重新绘制时,它就会被自动调用。当你的框架第一次渲染、调整大小、最大化(最小化后)等时,就会发生这种情况。
Actually you never invoke paint mathod yourself. It gets called automatically whenever the content pane of your frame needs to be repainted. It happens when your frame is rendered for the first time, resized, maximized (after being minimzed), etc.
如果您不知道 AWT/Swing(渲染)绘画 API 的工作原理,请阅读本文 - 在 AWT 和 Swing 中绘画。
If you are not aware of how AWT/Swing (render) painting API works then read this article - Painting in AWT and Swing.