我刚刚开始通过小程序创建一个门户游戏(是的,我知道它已经完全过时了,我应该使用 swing blah blah blah),到目前为止我只遇到了一个问题。浏览器/appletviewer 只会自动调用paint 和init。如果我想调用一个需要 keyevent 的方法,那是不可能的,因为 init 没有收到任何东西,而 paint 只收到了一个 Graphic。因此我不能调用方法thinkerbox,这很重要。到目前为止,这是我的代码(分为两个类):
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class portal extends Applet
{
public Image stickA;
public int x = 90;
public int y = 20;
public void init()
{
stickA = getImage( getDocumentBase(), "stick.jpg" );
}
public void thinkerbox( Graphics screen, KeyEvent e )
{
addKeyListener(new keyaction());
keyaction asdf = new keyaction();
asdf.useKeys( e, screen );
}
public void moveRight( Graphics screen )
{
addKeyListener(new keyaction());
screen.setColor( Color.WHITE );
screen.fillRect( x, y, 100, 100 );
x += 10;
paint( screen );
}
public void moveLeft( Graphics screen )
{
screen.setColor( Color.WHITE );
screen.fillRect( x, y, 100, 100 );
x -= 10;
paint( screen );
}
public void moveUp( Graphics screen )
{
screen.setColor( Color.WHITE );
screen.fillRect( x, y, 100, 100 );
y += 10;
paint( screen );
}
public void moveDown( Graphics screen )
{
screen.setColor( Color.WHITE );
screen.fillRect( x, y, 100, 100 );
y -= 10;
paint( screen );
}
public void paint( Graphics screen )
{
setBackground( Color.WHITE );
screen.setColor( Color.RED );
screen.fillOval( 20, 20, 40, 80 ); //red portal1
screen.fillOval( 200, 200, 40, 80 ); //red portal2
screen.drawImage( stickA, x, y, 100, 100, this );
}
}
第二个:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class keyaction extends KeyAdapter
{
public void useKeys( KeyEvent e, Graphics screen )
{
int keycode = e.getKeyCode();
portal p = new portal();
p.thinkerbox( screen, e );
if( keycode == KeyEvent.VK_LEFT )
{
p.moveLeft( screen );
}
else if( keycode == KeyEvent.VK_RIGHT )
{
p.moveRight( screen );
}
else if( keycode == KeyEvent.VK_UP )
{
p.moveUp( screen );
}
else if( keycode == KeyEvent.VK_DOWN )
{
p.moveDown( screen );
};
}
}
请帮忙?