9

这是我一直存在问题的代码。

package ca.rhinoza.game;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;

import javax.swing.JFrame;

public boolean running = false;


public class Game extends Canvas implements Runnable {

    private static final long serialVersionUID = 1L;

    public static final int WIDTH = 160;
    public static final int HEIGHT = WIDTH / 12 * 9;
    public static final int SCALE = 3;
    public static final String NAME = "Game";

    private JFrame frame;

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

        frame = new JFrame(NAME);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        frame.add(this, BorderLayout.CENTER);
        frame.pack();

        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public synchronized void start(){

        new Thread(this).start();

    }

    public synchronized void stop(){

    }

    public void run() {


    }


    public static void main(String[] args){

        new Game().start();
    }


}

我不知道它为什么这样做。

编辑: 我根据您的要求进行了编辑以查看更多代码。

4

2 回答 2

17

您在类之外声明一个字段:

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;

import javax.swing.JFrame;

public boolean running = false; /// <=============== invalid location 


public class Game extends Canvas implements Runnable { // <==== class starts here
    private static final long serialVersionUID = 1L;

    public static final int WIDTH = 160;
    public static final int HEIGHT = WIDTH / 12 * 9;
    public static final int SCALE = 3;
    public static final String NAME = "Game";
    ...

它必须放在一个类中:

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;

import javax.swing.JFrame;


public class Game extends Canvas implements Runnable { // <==== class starts here

    public boolean running = false; /// <=============== valid location

    private static final long serialVersionUID = 1L;

    public static final int WIDTH = 160;
    public static final int HEIGHT = WIDTH / 12 * 9;
    public static final int SCALE = 3;
    public static final String NAME = "Game";
    ...
于 2013-07-08T22:50:16.003 回答
2

你把

public boolean running = false;

在类定义之外,有效地在全局命名空间中。但是Java中没有全局变量。这是不合法的。

我会说,这是一个奇怪的错误信息。我希望编译器能提供更多。大意是classinterfaceenum因为一旦你开始陈述,public就可以遵循三个合法的事情。但是它就是这样啊。所以,编译器抱怨是的,我只是希望得到更多信息的错误消息。

于 2013-07-08T22:50:55.567 回答