Here is the program question.
Write a program that moves the ball in a panel. You should define a panel class for displaying the ball and provides the methods for moving the
button, left, right, up, and down.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Ex15_3 extends JFrame
{
//Keyboard Panel
private KeyboardPanel key = new KeyboardPanel();
//Buttons
private JButton jbtUp = new JButton("UP");
private JButton jbtDown = new JButton("DOWN");
private JButton jbtLeft = new JButton("LEFT");
private JButton jbtRight = new JButton("RIGHT");
//Create a panel
public Ex15_3()
{
//Using panel to group buttons
JPanel panel = new JPanel();
add(panel);
panel.add(jbtUp);
panel.add(jbtDown);
panel.add(jbtLeft);
panel.add(jbtRight);
//Adding buttons to panel
this.add(panel, BorderLayout.SOUTH);
//Add keyboard panel to accept and display user input
add(key);
//Set the focus
key.setFocusable(true);
//Up button listener
jbtUp.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
key.up();
}
});
//Down button listener
jbtDown.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
key.down();
}
});
//Left button listener
jbtLeft.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
key.left();
}
});
//Right button listener
jbtRight.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
key.right();
}
});
}
//Main method
public static void main(String[] args)
{
//Frame
Ex15_3 frame = new Ex15_3();
//Frame properties
frame.setTitle("Exercise15_3");
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//Inner class, KeyboardPanel for receiving key input
static class KeyboardPanel extends JPanel
{
//Declaring constants
private int x = 100;
private int y = 100;
private int radius = 5;
//Default key stroke
private char keyChar = 'Z';
//Move up
public void up()
{
y -= 10;
repaint();
}
//Move down
public void down()
{
y += 10;
repaint();
}
//Move left
public void left()
{
x -= 10;
repaint();
}
//Move right
public void right()
{
x += 10;
repaint();
}
public KeyboardPanel()
{
//Key input and Register listener
addKeyListener(new KeyAdapter()
{
//Override handler
public void keyPressed(KeyEvent k)
{
switch (k.getKeyCode())
{
case KeyEvent.VK_DOWN:
down();
break;
case KeyEvent.VK_UP:
up();
break;
case KeyEvent.VK_LEFT:
left();
break;
case KeyEvent.VK_RIGHT:
right();
break;
//Obtain the key pressed
default: keyChar = k.getKeyChar();
}
//Repaint panel
repaint();
}
});
}
//Drawing the ball
protected void paintComponent(Graphics B )
{
super.paintComponent( B );
//Setting the color of the ball
b.setColor(Color.blue);
//Painting the ball
b.fillOval(getWidth() / 2 - radius, getHeight() / 2 - radius, 2 * radius, 2 * radius);
}
}
}
Can anyone tell me where im going wrong ????
Thanks for your Help !!!!

New Topic/Question
Reply




MultiQuote



|