Giani Noyez
Giani Noyez

Reputation: 491

Swing not Drawing in Applet

I have to program a breakout game for school and I ran into a problem. I need to paint my 2D figures but I can't see them.

This is my applet. test() is a JPanel which I will link below.

public class Gamefield extends Applet{

test t;


@Override
public void init() {
    t = new test();
    setSize(1600, 900);

    Frame frame = (Frame)this.getParent().getParent();
    frame.setTitle("Breakout");



    add(t);
}
}

Here is my JPanel where I call repaint().

public class test extends JPanel implements Runnable {



public test(){

    setSize(1600,900);


    Thread thread = new Thread(this);
    thread.start();
}

@Override
public void run() {
    while(true){
        System.out.println("a");
        try{
            repaint();
            Thread.sleep(1000/60);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void paintComponent(Graphics g) {
    System.out.println("draw");
    super.paintComponents(g);
    g.setColor(Color.BLACK);
    g.drawOval(500,500,100,100);
    g.fillRect(100,100,100,100);
}

}

I hope that someone can help me out. I don't know what I can try to fix it.

Upvotes: 2

Views: 110

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168815

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

public class GameField extends JApplet {

    @Override
    public void init() {
        // Applet is FlowLayout by default, which does not stretch components
        // let's use GridLayout instead
        setLayout(new GridLayout()); 
        add(new test());
    }
}

class test extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        System.out.println("draw");
        // super.paintComponents(g);  // WRONG method!  Broken paint chain
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.drawOval(500, 500, 100, 100);
        g.fillRect(100, 100, 100, 100);
    }
}

Upvotes: 3

Related Questions