java启动:小程序未初始化错误。我如何解决这个问题?
我试图制作一个小程序作为学校的一个项目,但遇到了这个我以前从未见过的错误。任何建议都是非常受欢迎的,我已经挣扎了几个小时也没有用。另外,这是我在Java中的第一个大项目,所以任何关于编码和风格的其他建议都是非常受欢迎的。我的IDE是blueJ,如果有必要,我会在applet查看器中运行它。干杯
import java.awt.*;
import javax.swing.*;
import java.lang.*;
import java.util.*;
import java.awt.event.*;
public abstract class Renderer extends JApplet implements KeyListener
{
public PlayerShip playerShip;
public static final int CANVAS_SIZE=500;
public static final int FRAMES_PER_SECOND = 20;
public static final int SKIP_TICKS = 1000 / FRAMES_PER_SECOND;
public void initLevel(){
playerShip= new PlayerShip(CANVAS_SIZE);
}
@Override
public void keyPressed(KeyEvent e){
if (e.getKeyCode()== KeyEvent.VK_RIGHT){
playerShip.moveRight();
}
else if (e.getKeyCode()== KeyEvent.VK_LEFT){
playerShip.moveLeft();
}
repaint();
}
public void paint(Graphics g){
int sleep_time = 0;
int next_game_tick = 0;
long sleepTime;
boolean Game= true;
long startTime= System.currentTimeMillis();
setSize(CANVAS_SIZE, CANVAS_SIZE);
while(Game== true){
initLevel();
int leftSide=playerShip.getLeftBound();
int width=playerShip.getWidth();
int topSide=playerShip.getTopBound();
int height=playerShip.getHeight();
g.setColor(Color.blue);
g.fillRect(0, 0, CANVAS_SIZE, CANVAS_SIZE);
g.setColor(Color.orange);
g.fillRect (leftSide, topSide, width, height);
long timeElapsed = System.currentTimeMillis() - startTime;
next_game_tick += SKIP_TICKS;
sleepTime= next_game_tick - timeElapsed;
try{
Thread.sleep(sleepTime);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
}
}
编辑:这也是玩家的职业
public class PlayerShip
{
// instance variables - replace the example below with your own
public static final int SIZE= 20;
public int shipX;
public int shipY;
public int shipLeft;
public int shipRight;
public PlayerShip(int canvasSize)
{
shipX= canvasSize/2;
shipY= canvasSize*3/4;
}
public void moveLeft(){
shipX -=1;
}
public void moveRight(){
shipX+=1;
}
public int getLeftBound(){
int leftSide = Math.round(shipX - (SIZE/2));
return (leftSide);
}
public int getWidth(){
return SIZE;
}
public int getTopBound(){
int topSide = Math.round(shipY - (SIZE/2));
return (topSide);
}
public int getHeight(){
return SIZE;
}
}
# 1 楼答案
实现
KeyListener
一个问题可能是,您只实现了^{} 接口所需的三种方法中的一种。你做了
keyPressed
,但省略了keyTyped
和keyReleased
进口
您可能需要为
Color
类添加一个显式的import
来识别其常量按照惯例,Java中的常量都是用大写字母命名的。所以,
Color.BLUE
命名约定
这不是编译器或小程序的问题,但为了让其他程序员阅读您的代码,您应该遵循Java命名约定。所以
boolean Game
应该以小写字母开头。此外,布尔值通常以is
前缀命名,所以boolean isGame
。我想你可以想出一个更具描述性的措辞顺便说一下,为了简洁起见,把
while ( isGame == true )
缩短为while ( isGame )
一个更严重的问题是:在
while
循环中使用的这个isGame
变量永远不会改变其状态。所以你的while
循环是无限的运行
在做了上述更改后,我看到您的小程序在macOS Mojave的MacBook Pro上通过AppletViewerapp version 1.0,使用IntelliJIDE和Java 8(Zul系统的ZuluJVM)启动
顺便说一句,在我看来,你正在用你的行
Thread.sleep(sleepTime);
睡主GUI线程。我不是applet或AWT方面的专家,但正如我所记得的,你应该永远不要睡在主GUI线程上…还有
我还要补充一点,即Java Applet技术正在被网络浏览器制造商、Oracle和Java社区逐步淘汰。这个项目很适合学习。但在实际工作中,您可能会想了解OpenJFX,并使用jlink绑定Java运行时