I've just started creating a portal game through applet (yes I know it's totally outdated and I should be using swing blah blah blah), and so far I've only encountered one problem. The browser/appletviewer only calls paint and init automatically. If I want to call a method which needs a keyevent, that can't happen because init doesn't receive anything and paint only receives a Graphic. Therefore I can't call the method thinkerbox, which is kind of important. Here is my code so far (in two classes):
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 );
}
}
And the second one:
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 );
};
}
}
Help please?