Reputation: 176
I'm creating a JFrame window, creating a 'ball' object, and adding this ball object to the jframe window. What's the problem exactly?
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);
}
}
Basically, when I run this program, 'super.paint(g)' gets called over and over again and I don't know why this is. I haven't set the ball to move in a timer or anything so why's the problem occurring?
Upvotes: 2
Views: 469
Reputation: 285405
As Abhinav states, the problem is that super.paint(g);
is re-starting the painting chain which then calls the JPanel's paintComponent(g)
method which calls super.paint(g)
which calls the JPanel's paintComponent(g)
method which calls... and on and on
The solution is simple -- call the correct super method, the one that matches the painting method that you're calling:
@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);
}
Upvotes: 3
Reputation:
super.paint() calls the paintComponent() function, so obvioulsy, this is an endless recursion. Therefore, you will never get out of the code. Probably call the function at an interval of time.
Upvotes: 2