我刚刚开始通过applet创建门户游戏(是的,我知道它已经完全过时,我应该使用摇摆等等等等),到目前为止我只遇到过一个问题。浏览器/ 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 );
};
}
}
请帮忙吗?
答案 0 :(得分:1)
建议:
repaint()
paintComponent(Graphics g)
方法使用类字段来决定在哪里绘制。