简体   繁体   中英

Run Method is called, but Wont Draw

If you run the program, you can see that it prints "Run() method is called", when the run gets called. But the System.out.println() inside the if statement does not get called nor the render() method gets called.

import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;

public class Game extends Canvas implements Runnable {
public static int WIDTH = 300;
public static int HEIGHT = WIDTH / 16*9;
public static int SCALE = 3;
public static String TITLE = "";

private Thread thread;
private boolean running = false;
private JFrame frame;


public void start() {
    if(running) return;

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

public void stop() {
    if(!running) return;

    try{
        thread.join();
    }catch(InterruptedException e) {
        e.printStackTrace();
    }
}

public void run() {
    System.out.println("Run() has been called");
    long lastTime = System.nanoTime();
    long timer = System.currentTimeMillis();
    double ns = 1000000000.0 / 60.0;

    double delta = 0;
    int ticks = 0;
    int fps = 0;

    while(running) {
        long now = System.nanoTime();
        delta += (now-lastTime) / ns;
        lastTime = now;
        while(delta >= 1) {
            tick();
            ticks++;
            delta--;
        }
        render();
        fps++;
        if(System.currentTimeMillis() - timer > 1000) {
            timer += 1000;
            System.out.println("Fps: " + fps + " Ticks: " + ticks);
            fps = 0;
            ticks = 0;
        }
    }
    stop();
}

public void tick() {        
}

public void render() {
    BufferStrategy bs = getBufferStrategy();
    if(bs==null) {
        createBufferStrategy(3);
        return;
    }

    Graphics g = bs.getDrawGraphics();
    g.fillRect(36, 25, 25, 25);
    g.dispose();
    bs.show();
}

public Game() {
    setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));

    frame = new JFrame();
}

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

    game.frame.setResizable(false);
    game.frame.setTitle("SPACE ADAPT PRE-ALPHA 0.001");
    game.frame.add(game);
    game.frame.pack();
    game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    game.frame.setLocationRelativeTo(null);
    game.frame.setVisible(true);

    game.start();
}
}

You never set running to true, then it's false. As a side note not related with this question but most of swing components methods are not thread-safe so calling in another thread that is not the Event Dispatch Thread would not work as you expected.

Read more Concurrency in Swing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM