首页 > 解决方案 > 绘制方法执行多次

问题描述

为什么在我运行我的代码时这个绘图函数会执行很多次?

我试图只运行一次这段代码,但它执行了很多次,我不知道为什么会这样!

public class DrawFrame extends JFrame {

@Override
public void paint(Graphics g) {

    System.out.println("hello Frame");
}
}

public class NJFrame {
public static void main(String[] args) {


    DrawFrame NJFrame = new DrawFrame();
    NJFrame.setSize(1000, 1000);
    NJFrame.setVisible(true);
    NJFrame.setLocation(400, 150);
    NJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

在此处输入图像描述

标签: javaswing

解决方案


好吧,您的代码多次操纵 JFrame:

DrawFrame NJFrame = new DrawFrame(); // (1) Create the frame
NJFrame.setSize(1000, 1000);         // (2) Resize the frame
NJFrame.setVisible(true);            // (3) Show the frame
NJFrame.setLocation(400, 150);       // (4) Move the frame

似乎这些操作中的每一个都会触发一个绘制事件,您的paint方法会处理该事件。


推荐阅读