having JPanel in a JApplet problems

Can someone please help me out here - I’m obviously doing something stupid, but can’t think what and am going round in circles.

This is a simple applet (actually more of a craplet) that should show a red screen, but doesn’t. It’s a simplified version of something bigger that equally doesn’t work.

The applet class:

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

public class MyApplet extends JApplet implements Runnable {
    MyPanel myPanel;
    
    public void init(){
        myPanel=new MyPanel();
        this.getContentPane().add(myPanel);
        new Thread(this).run();
    }
    
    public void run(){
        while(true){
            myPanel.repaint();
            try{Thread.sleep(50);}catch(Exception e){}
        }
    }
    
}

and the panel class:

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

public class MyPanel extends JPanel {

    public void paint(Graphics g){
        Graphics2D g2d=(Graphics2D)g;
        g2d.setColor(Color.RED);
        g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
    }
}

Any ideas ?

Thanks

new Thread(this).start();

;D

A good rule of thumb is if you think something doesn’t work make sure that’s the actual cause first. A few print lines could have told you that your paint wasn’t getting called at all.

hmm, you’re absolutely right !

Funny thing though, I’d put in a println statement in the while loop of the run() method, and that prints whether you use start() or run(), but if I put the same println in the paint method of the panel, then that only gets called with start()

Anyway, sadly that’s not the cause of my problem in my game, I was using start() there anyway, and I know the game thread is running there - need to do some more thinking

Thanks though ;D

sussed my problem - I’d got a line somewhere in the Main class in the init of the applet where I’d set JApplet applet=new Main() and was then calling Main.applet.repaint() so it was calling repaint on some random instantiation of the applet class that wasn’t the applet on the screen.

changing that first line to JApplet applet=this; fixes it perfectly.

Onto double-buffering now, it looks horrible at the moment !

Yup, that’s a good call with assigning the myPanel. Sorry I didn’t notice it earlier; I typically use apps.