java - Paint 组件陷入无限循环,导致 stackoverflow 错误。为什么是这样?

标签 java swing graphics

我正在创建一个 JFrame 窗口,创建一个“球”对象,并将该球对象添加到 jframe 窗口中。具体是什么问题?

public class Main {
    public static void main(String[] args){
        JFrameWindow j= new JFrameWindow(300,500);
        Ball b = new Ball(150,200,10,20);
        j.add(b);
    }
}

import javax.swing.*;
import java.awt.*;

public class JFrameWindow extends JFrame {
    int width;
    int height;

    public JFrameWindow(int width,int height){
        this.width=width;

    //blah

import javax.swing.*;
import java.awt.*;

public class Ball extends JPanel{
    int sX,sY;
    Color color;
    int speed;
    int height;
    int width;

    public Ball(int sX,int sY,int height,int width){
        this.sX=sX;
        this.sY=sY;
        this.color=color;
        this.speed=speed;
        this.height=height;
        this.width=width;
    }

    public void paintComponent(Graphics g){
        super.paint(g);
        Graphics2D g2d=(Graphics2D)g;
        //g2d.setColor(color.RED);
        g2d.fillOval(sX,sY,width,height);
    }
}

基本上,当我运行这个程序时,“super.paint(g)”被一遍又一遍地调用,我不知道这是为什么。我还没有设置球在计时器或任何东西中移动,那么为什么会出现问题?

最佳答案

正如 Abhinav 所说,问题在于 super.paint(g); 正在重新启动绘画链,然后调用 JPanel 的 paintComponent(g) 方法,该方法调用 super.paint(g) ,它调用 JPanel 的 paintComponent(g) 方法,该方法调用...等等

解决方案很简单 - 调用正确的 super 方法,即与您正在调用的绘画方法相匹配的方法:

@Override
protected void paintComponent(Graphics g) { // protected, not public

    // super.paint(g);       // ******** REMOVE *********
    super.paintComponent(g); // ******** ADD *********

    Graphics2D g2d = (Graphics2D) g;
    g2d.fillOval(sX, sY, width, height);
}

关于java - Paint 组件陷入无限循环,导致 stackoverflow 错误。为什么是这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55430443/

相关文章:

java传递JFrame可以接受吗?

android - 我需要了解为什么 setImageMatrix 不起作用

java - Eclipse 中带有 WindowBuilder 的应用程序窗口

java - Java 中对 MacOS X 的 native Swing 菜单栏支持

c# - 如何在点击事件中绘制图像?

java - java中的颜色褪色

java - 如何使用 Web 服务和 EclipseLink 作为 JPA 提供程序更新数据库?

java - 重命名时文件不会被删除

JavaFX JAR 文件无法运行

java - JBox2d 中有 RopeJoint 吗?