Paint组件卡在无限循环中,从而导致stackoverflow错误。为什么会这样?

时间:2019-03-30 10:21:21

标签: java swing graphics

我正在创建一个JFrame窗口,创建一个'ball'对象,并将此ball对象添加到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)',但我不知道为什么会这样。我没有将球设置为可以在计时器中移动,所以为什么会出现问题?

2 个答案:

答案 0 :(得分:3)

正如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);
}

答案 1 :(得分:2)

super.paint()调用paintComponent()函数,因此很麻烦,这是无休止的递归。因此,您将永远不会脱离代码。可能每隔一段时间调用该函数。

相关问题