如何制作Java Canvas游戏循环

时间:2016-08-31 09:30:48

标签: java swing loops nullpointerexception

我一直在尝试在画布上创建一个运行渲染(图形g)和逻辑()的java游戏循环,但它不起作用。

我已经尝试制作一个运行这两个函数的脚本,然后再次调用它来创建一个循环。

提前致谢。

我试过了:

git checkout master
git log
# find the SHA-1 hash of merge commit A (e.g. d82n93kd...)
git revert d82n93kd -m 1

}

我从日食中得到的错误是:

public class Canvas extends JPanel {
static GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
static int width = gd.getDisplayMode().getWidth();
static int height = gd.getDisplayMode().getHeight();
//Get the system time
long lastTime = System.nanoTime();
//Specify how many seconds there are in a minute as a double
//store as a double cause 60 sec in nanosec is big and store as final so it can't be changed
final double ticks = 60D;
//Set definition of how many ticks per 1000000000 ns or 1 sec
double ns = 1000000000 / ticks;    
double delta = 0;

public static void main(String[] args) {
    JFrame frame = new JFrame("Zombie Run");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new Canvas());
    frame.setSize(width, height);
    frame.setVisible(true);
    loop();
}

public static void loop() {
    logic();
    render(g);
    loop();
}
public static void render(Graphics g) {
    System.out.println("Running Render");
    g.setColor(Color.BLUE);
    g.fillRect(0, 0, 800, 500);

}
public static void logic() {
    System.out.println("Logic");

}

2 个答案:

答案 0 :(得分:1)

您可以使用Swing Timer。 while循环和Thread.sleep只会导致GUI冻结。

我使用Timer类做了一个例子。它创建一个延迟为42毫秒的计时器。每次延迟之后,它都会执行ActionListener内的代码。该示例将随机矩形绘制到面板上,有点像一个linux屏幕保护程序:PI认为你不必担心我是如何特别做到这一点,这只是为了说明如何使用Timer

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Foo {

    public static void main(String[] args) throws IOException {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Foo().createAndShowGUI();
            }
        });
    }

    public void createAndShowGUI() {
        DrawingPanel panel = new DrawingPanel();

        Timer timer = new Timer(42, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                panel.addNewRectangle();
                panel.repaint();
            }
        });
        timer.start();

        JFrame frame = new JFrame("Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.setSize(800, 600);
        frame.setVisible(true);
    }

    private class GameRectangle extends Rectangle {
        private Color color;

        public GameRectangle(int x, int y, int width, int height, Color color) {
            setBounds(x, y, width, height);
            setColor(color);
        }

        public void draw(Graphics2D context) {
            context.setColor(getColor());
            context.fill(this);
        }

        public Color getColor() {
            return color;
        }

        public void setColor(Color color) {
            this.color = color;
        }
    }

    private class DrawingPanel extends JPanel {
        private final Random RANDOM = new Random();
        private ArrayList<GameRectangle> rectangles;

        public DrawingPanel() {
            setRectangles(new ArrayList<>());
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g.create();
            for (GameRectangle rectangle : getRectangles()) {
                rectangle.draw(g2);
            }
            g2.dispose();
        }

        public void addNewRectangle() {
            getRectangles().add(createRandomRectangle());
        }

        private Color createRandomColor() {
            return new Color(RANDOM.nextInt(255), RANDOM.nextInt(255), RANDOM.nextInt(255));
        }

        private GameRectangle createRandomRectangle() {
            return new GameRectangle(RANDOM.nextInt(getWidth()), RANDOM.nextInt(getHeight()), RANDOM.nextInt(420),
                    RANDOM.nextInt(420), createRandomColor());
        }

        public ArrayList<GameRectangle> getRectangles() {
            return rectangles;
        }

        public void setRectangles(ArrayList<GameRectangle> rectangles) {
            this.rectangles = rectangles;
        }
    }

}

答案 1 :(得分:0)

使用java.lang.Threadjava.lang.Runnable

在您的班级中实施Runnable并创建一个帖子。 请记住实现run()方法。

public class Canvas extends JPanel implements Runnable{
    Thread mainThread = new Thread(this); //Creates a new thread with Canvas runnable object.

    //code

    @Override
    public void run(){}
}

所以,在main方法中我们启动线程。

public static void main(String[] args){
    //your frame creation and initialization code.

    mainThread.start(); //starts the thread.
}

所以你已经开始了这个主题。现在线程将进入run()方法。

boolean isStarted = false;
public void run(){
    isStarted = true;
    while(isStarted){
        logic();
        render(g);
    } /* The thread will return in this loop each has finished a task */
      // It's useless to call this method because the thread does all.
      // Leave it to the thread.
}

使用线程因为swing不是线程安全的!!!!!!!!

抛出NullPointerException,因为未初始化Graphics。