我正在使用 java 中的 swing 开发 2D 平台游戏,我目前正在开发游戏框架。我正在测试 reapaint() 和 draw 函数,但它们不起作用,我一无所知。这是我的代码:
窗口.java
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Window extends JFrame {
public Window() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(1000, 1000);
this.setVisible(true);
this.setTitle("Infiltrator");
this.setLocationRelativeTo(null);
this.setContentPane(new Framework());
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{ new Window(); }
}
);
}
}
面板.java
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public abstract class Panel extends JPanel {
public Panel() {
this.setDoubleBuffered(true);
this.setFocusable(true);
/*
*
if(false)
{
BufferedImage blankCursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(blankCursorImg, new Point(0, 0), null);
this.setCursor(blankCursor);
}
*
*/
}
public static void Draw(Graphics2D g2d) {
}
@Override
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
super.paintComponent(g2d);
Framework.Draw(g2d);
}
}
框架.java
import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JFrame;
public class Framework extends Panel {
private static long beginTime, takenTime, sleepTime;
private static long secInNano = 1000000000L;
private static long secInMilli = 1000000L;
private static long fps = 60L;
private static long fpsTime = secInNano / fps;
public static enum GameState {STARTING, MAINMENU, PLAYING, OVER};
public static GameState gameState;
public Framework ()
{
super();
Thread gameThread = new Thread() {
@Override
public void run(){
mainLoop();
}
};
gameState = GameState.STARTING;
gameThread.start();
}
private void mainLoop() {
while (gameState != GameState.OVER) {
beginTime = System.nanoTime();
switch (gameState) {
case STARTING:
LoadandInit();
break;
case MAINMENU:
MainMenu.Update();
break;
case PLAYING:
break;
default:
System.out.println("Ok, somebody messed up.");
break;
}
repaint();
takenTime = System.nanoTime() - beginTime;
sleepTime = (fpsTime - takenTime) / secInMilli;
if (sleepTime < 10)
sleepTime = 10;
try {
Thread.sleep(sleepTime);
} catch (InterruptedException ex) { }
}
}
private static void LoadandInit() {
gameState = GameState.MAINMENU;
}
public static void Draw(Graphics2D g2d) {
g2d.setColor(Color.BLACK);
g2d.drawString("DEARP", 0, 0);
}
}