好的,所以我想知道是否有人能告诉我哪里出错了。
我有一个名为Game的JApplet运行正常,如果我在eclipse中使用AppletViewer和一个名为GUI的JFrame运行它来保存JApplet。以下是两个代码:
PS。我从Game中删除了大部分代码,使其变小,现在只是基本的。
Game.java:
package com.ion.brickdodge;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JApplet;
public class Game extends JApplet implements Runnable{
private static final long serialVersionUID = 1L;
Image man1;
Image man2;
Image cman;
int WIDTH = 250;
int HEIGHT = 350;
int lives = 3;
int spx = WIDTH / 2;
int score = 0;
Image dbImage;
Graphics dbg;
public void init () {
setSize (WIDTH, HEIGHT);
setFocusable(true);
setBackground(Color.LIGHT_GRAY);
man1 = getImage(getCodeBase(), "res/man1.png");
man2 = getImage(getCodeBase(), "res/man2.png");
cman = man1;
}
public void start() {
Thread th = new Thread(this);
th.start();
}
public void run() {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while(true){
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
}
public void paint(Graphics g) {
g.drawImage(cman, spx, 320, this);
g.setColor(Color.BLACK);
g.drawString("Score: " + score, 5, 10);
g.drawString("Lives: " + lives, 5, 25);
}
public void update(Graphics g){
if (dbImage == null)
{
dbImage = createImage (this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics ();
}
dbg.setColor (getBackground ());
dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
dbg.setColor (getForeground());
paint (dbg);
g.drawImage (dbImage, 0, 0, this);
}
}
这是GUI.java:
package com.ion.brickdodge;
import java.awt.BorderLayout;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GUI {
public static void main(String args[]) {
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000, 1000);
JPanel panel = new JPanel(new BorderLayout());
frame.add(panel);
JApplet applet = new Game();
panel.add(applet, BorderLayout.CENTER);
applet.init();
frame.pack();
frame.setVisible(true);
}
}
错误GUI.java在我运行时抛出...
Exception in thread "main" java.lang.NullPointerException
at java.applet.Applet.getCodeBase(Unknown Source)
at com.ion.brickdodge.Game.init(Game.java:30)
at com.ion.brickdodge.GUI.main(GUI.java:22)
非常感谢任何帮助
答案 0 :(得分:3)
我会回答这个问题:我认为更好的解决方案是将GUI设置为创建JPanel。然后,如果您希望将GUI作为applet运行,您只需创建JPanel并将其放在JApplet的contentPane中。同样,如果你想创建一个JFrame,那么创建你的JPanel并将它放在JFrame的contentPane中。
其他问题:
答案 1 :(得分:3)
注意:如果问题是“为什么会这样?”答案是JVM会自动为applet设置applet上下文和存根。但除非将applet加载到网页中,否则不会发生这种情况。如果你自己加载它,你需要实现,实例化&附上那些设施。
一旦你掌握了applet元素通常提供的细节,就不是很难了。
(OTOH最好的策略是将游戏转换为面板,将其放入框架中,然后使用JWS启动它。)