-
applet problem
hello, I am a very dumb java-newbie with -probably- a very stupid question:
the case--> i have made an applet with 4 buttons standing for 4 direction, and a rectangle that needs to move in the submitted direction but there something wrong with the co-ordinates. i can't figure it out: only 'right' seems to work properly... its driving me insane!!!:confused:
here is the code
thx
<code>
public class AppletTest extends JApplet{
int x = 20;
int y = 220;
int width = 40;
int height = 40;
int a=0;
public class ButtonPanel extends JPanel {
Timer t = new Timer(500, new TimerHandler());
public ButtonPanel(){
setLayout(null);
setBackground(Color.blue);
JButton btnUp = new JButton("Up");
JButton btnDown = new JButton("Down");
JButton btnLeft = new JButton("Left");
JButton btnRight = new JButton("Right");
JButton btnStart = new JButton("Start");
JButton btnStop = new JButton("Stop");
btnUp.addActionListener(new btnUpHandler());
btnDown.addActionListener(new btnDownHandler());
btnLeft.addActionListener(new btnLeftHandler());
btnRight.addActionListener(new btnRightHandler());
btnUp.setBounds(215,10,70,30);
btnDown.setBounds(215,70,70,30);
btnLeft.setBounds(145,40,70,30);
btnRight.setBounds(285,40,70,30);
btnStart.setBounds(1,1,70,30);
btnStop.setBounds(1,40,70,30);
add(btnUp);
add(btnDown);
add(btnLeft);
add(btnRight);
}
class TimerHandler implements ActionListener{
public void actionPerformed (ActionEvent e){
switch(a){
case 1:x-=1;
case 2:y+=1;
case 3:x+=1;
case 4:y-=1;
case 0:
}
repaint();
}
}
public void paint(Graphics g){
super.paint(g);
g.fillRect(x, y,width, height);
}
class btnUpHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
t.stop();
a=1;
t.start();
}
}
class btnRightHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
t.stop();
a=2;
t.start();
}
}
class btnDownHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
t.stop();
a=3;
t.start();
}
}
class btnLeftHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
t.stop();
a=4;
t.start();
}
}
}
public void init(){
setSize(500, 300);
JPanel pnlButtons = new ButtonPanel();
setContentPane(pnlButtons);
}
}
</code>
-
Look at the switch statement. It needs break after the case if you do not want the following case to be executed.
Add a println() at the end of the switch statement to display the values of x and y to see if they are getting the values you expect.
-
thx norm, and i also will post following applet-related questions in the therefor created section, i ve just noticed it :D