GoldShovel
GoldShovel

Reputation: 35

JFrame screen is flashing white and black

I have a problem where my JFrame is constantly flashing white and black, but I only set the colour to black. I think it has to do with the while (running) {} bit.

It just turns white and black forever, until I close it. I really don't know what is going on.. I only just started to use JFrame so I'm sure I have just put some wrong code.

public class Game extends Canvas implements Runnable {

    private static final long serialVersionUID = 1L;

    public static int width = 300;
    public static int height = width / 16 * 9;
    public static int scale = 3;
    public static boolean running = false;

    private Thread thread;

    private JFrame frame;

    public Game() {
        Dimension window = new Dimension(width * scale, height * scale);
        setPreferredSize(window);
        frame = new JFrame();
    }

    public synchronized void start() {
        running = true;
        thread = new Thread(this, "Display");
        thread.start();
    }

    public synchronized void stop() {
        try {
            running = false;
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        while (running) {
            render();
        }
    }

    public void update() {

    }

    public void render() {
        BufferStrategy buffer = getBufferStrategy();

        if (buffer == null) {
            createBufferStrategy(3);
            return;
        }

        Graphics g = buffer.getDrawGraphics();

        g.setColor(Color.BLACK);
        g.drawRect(0, 0, getWidth(), getHeight());

        g.dispose();
        buffer.show();
    }

    public static void main(String[] args) {
        Game game = new Game();

        game.frame.setResizable(false);
        game.frame.setTitle("Game");
        game.frame.add(game);
        game.frame.pack();
        game.frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        game.frame.setLocationRelativeTo(null);
        game.frame.setVisible(true);

        game.start();
    }
}

Upvotes: 0

Views: 231

Answers (1)

GoldShovel
GoldShovel

Reputation: 35

Solved it myself... I used the method drawRect() And I read the documentation page and it says it only draws the outline of the rectangle.. So I just did drawRect() Also I changed the buffer to 2.

Sorry for wasting your time.

Upvotes: 1

Related Questions