gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:24:49 25 4
gpt4 key购买 nike

我正在创建一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com