Repaint methods are not being called and i get a blank frame as output

22 views Asked by At

I created two classes rect and ball which work fine when executed individually. Later I combined these two classes into a single class called game and added it to the frame. Following this change, I am not getting the output.

public class rect extends JPanel implements KeyListener{//to create a bat
int x=1,y=1;
int xa=1,ya=1;
int max=0,min=0;
public rect(){


    addKeyListener(this);

}


public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.setColor(Color.blue);

    g.fillRect(x,440 , 125,20);

}


public void keyPressed(KeyEvent e) {

        int c=e.getKeyCode();
          if(c==KeyEvent.VK_LEFT){

                if(min!=1){
                    xa=-10;
                    move();
                }
          }
          if(c==KeyEvent.VK_RIGHT){

                if(max!=1){
                    xa=10;
                    move();

                }

          }  
}

public void keyReleased(KeyEvent e) {
    xa=0;

}
public void keyTyped(KeyEvent e) {



}

    public static void main(String c[]){

    JFrame f =new JFrame();
    f.setSize(800, 500);
    f.setVisible(true);
    f.setTitle("DX BALL");
    f.setResizable(false);
    f.setFocusable(false);
    **i hav created the class and added but i am uncertain whether that gg object is added to the frame or not because i am getting a blank frame**
    game gg=new game();
    f.add(gg);
    gg.rr.setFocusable(true);
    while(true){
        gg.repaint();

repaint is not calling its member object repaint function wats wrong

        try {
            Thread.sleep(15);

        } catch (InterruptedException e) {

            e.printStackTrace();
        }


    }


}

public void move() {

    x=x+xa;
    if(x<1||x>664){
        if(x>650){
            max=1;
            min=0;
        }
        else{
            min=1;
            max=0;
        }
    }
    else{   

    max=0;min=0;


    }

}

}

class ball extends JPanel{//to create a ball
int x,y;
private int xa=1;
private int ya=1;

public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.fillOval(x, y,30,30);
}

public void update(Graphics g){
    paint(g);
}

void move(){
    if (x + xa < 0)
        xa = 1;
    if (x + xa > 760)
        xa = -1;
    if (y + ya < 0)
        ya = 1;
    if (y + ya >420)
        ya = -1;
    x=x+xa;
    y=y+ya; 
}
}
class game extends JPanel{//class that has both bat an ball

This is the class where problem arrises. I haev individually checked the ball and rect class it works

rect rr;
ball bb;
game(){
    rr=new rect();
    bb=new ball();
}
void paintComponent(Graphics g){
    super.paintComponent(g);
      *i am not getting even a single object being painted*
    rr.repaint();
    bb.repaint();
    bb.move();
}
}
0

There are 0 answers