JAVA PROGRAM TO MOVE-A-BALL IN RESPONSE TO UP/DOWN/LEFT/RIGHT BUTTONS, AS WELL AS THE 4 ARROW KEYS.
package
com.company;
import
java.awt.Button;
import
java.awt.Color;
import
java.awt.event.*;
import
java.awt.Graphics;
import
java.applet.Applet;
public class
MyApplet extends Applet implements ActionListener, KeyListener
{
Button up_button,down_button, left_button,
right_button;
int x, y;
String direction="Still";
public void init()
{
x=0; y=0;
setLayout(null);
up_button = new Button("UP");
down_button = new
Button("DOWN");
left_button = new
Button("LEFT");
right_button = new
Button("RIGHT");
add(up_button);
up_button.setBounds(160, 200, 66, 30);
up_button.addActionListener(this);
add(down_button);
down_button.setBounds(160, 270, 66,
30);
down_button.addActionListener(this);
add(left_button);
left_button.setBounds(125, 235, 66,
30);
left_button.addActionListener(this);
add(right_button);
right_button.setBounds(200, 235, 66,
30);
right_button.addActionListener(this);
addKeyListener(this);
setFocusable(true);
setBackground(Color.blue);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillOval(x , y, 45, 45);
}
public void actionPerformed(ActionEvent ef)
{
if (ef.getSource()==up_button)
{
if(y<=0)
{
y=850;
repaint();
}
else
{
y-=5;
repaint();
}
}
else if (ef.getSource()==down_button)
{
if((y)>=850)
{
y=0;
repaint();
}
else
{
y+=5;
repaint();
}
}
else if (ef.getSource()==left_button)
{
if(x<=0)
{
x=850;
repaint();
}
else
{
x-=5;
repaint();
}
}
else if (ef.getSource()==right_button)
{
if((x)>=850)
{
x=0;
repaint();
}
else
{
x+=5;
repaint();
}
}
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
int key= e.getKeyCode();
if(key==KeyEvent.VK_UP)
{
if(y<=0)
{
y=850;
repaint();
}
else
{
y-=5;
repaint();
}
}
else if(key==KeyEvent.VK_DOWN)
{
if(y>=850)
{
y=0;
repaint();
}
else
{
y+=5;
repaint();
}
}
else if(key==KeyEvent.VK_LEFT)
{
if(x<=0)
{
x=850;
repaint();
}
else
{
x-=5;
repaint();
}
}
else if(key==KeyEvent.VK_RIGHT)
{
if(x>=850)
{
x=0;
repaint();
}
else
{
x+=5;
repaint();
}
}
}
@Override
public void keyTyped(KeyEvent e) {
}
}
/*
<applet
code="MyApplet.class" height=500 width=500 >
</applet>
*/
OUTPUT :
Labels: AS WELL AS THE 4 ARROW KEYS., JAVA PROGRAM TO MOVE-A-BALL IN RESPONSE TO UP/DOWN/LEFT/RIGHT BUTTONS



