首页 > 解决方案 > 包理解问题

问题描述

我正在用java制作游戏,所以我需要一些帮助。我想在包中组织我的代码,但我不明白属于哪个 .java 文件。我的文件组织

应用程序.java

package main;
import engine.io.Window;
import org.lwjgl.glfw.GLFW;
public class App implements Runnable {
    public Thread game;
    public static Window window;
    public static final int WIDTH = 1280, HEIGHT = 760;
    public void start() {
        game = new Thread(this, "game");
        game.start();
    }
    public static void init() {
        window = new Window(WIDTH, HEIGHT, "Game");
        window.create();
    }
    public void run() {
        init();
        while (!window.shouldClose()) {
            update();
            render();
        } 
    }
    private void update() {
        window.update();
    }
    private void render() {
        window.swapBuffers();
    }
    public static void main(String[] args) {
        new App().start();
    }
}

和 Window.java

package engine.io;

import org.lwjgl.glfw.GLFW;
import org.lwjgl.glfw.GLFWVidMode;

public class Window {
    private int width, height;
    private String title;
    private long window;
    public int frames;
    public static long time;

    public Window(int width, int height, String title) {
        this.width = width;
        this.height = height;
        this.title = title;
    }

    public void create() {
        if (!GLFW.glfwInit()) {
            System.err.println("ERROR: GLFW wasn't initializied");
            return;
        }

        window = GLFW.glfwCreateWindow(width, height, title, 0, 0);

        if (window == 0) {
            System.err.println("ERROR: Window wasn't created");
            return;
        }

        GLFWVidMode videoMode = GLFW.glfwGetVideoMode(GLFW.glfwGetPrimaryMonitor());
        GLFW.glfwSetWindowPos(window, (videoMode.width() - width) / 2, (videoMode.height() - height) / 2);
        GLFW.glfwMakeContextCurrent(window);


        GLFW.glfwShowWindow(window);

        GLFW.glfwSwapInterval(1);

        time = System.currentTimeMillis();
    }

    public void update() {
        GLFW.glfwPollEvents();
        frames++;
        if (System.currentTimeMillis() > time + 1000) {
            GLFW.glfwSetWindowTitle(window, title + " | FPS: " + frames);
            time = System.currentTimeMillis();
            frames = 0;
        }
    }

    public void swapBuffers() {
        GLFW.glfwSwapBuffers(window);
    }

    public boolean shouldClose() {
        return GLFW.glfwWindowShouldClose(window);
    }
}

我收到以下错误:声明的包“main”与预期的包“ourRTS”不匹配,并且无法解析导入引擎。

标签: javapackagenaming

解决方案


将一个目录视为“默认”或“主”目录;无论它是什么,它的名称都不必与项目相关。它可以在磁盘的根目录或不在磁盘的根目录,它可以从根目录向下许多级别,它的位置无关紧要。

应用程序中每个包中的第一个名称(在第一个句点之前)是该“默认”目录之外的目录名称。每个包中的连续名称(每个句点之后)是前一个包名称段下的目录级别。

你有'engine.io',所以在你的默认目录下你将有目录“engine”,在那个目录下有一个名为“io”的目录。包“engine.io”中的所有 java 文件都必须在 io 目录中。

这些是目录和包名称,因为它们必须存在于您的 java 文件和项目中。在 Eclipse 中,默认目录通常命名为“src”,有时顶级包名目录位于该目录下。我不知道你的是否是这样组织的,但这是一种常见的方式。


推荐阅读