Hello, I need to move an object with the arrow key.
This is my object class:
import java.awt.Color; import java.awt.Graphics; import java.awt.Paint; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class matka { private int x; private int y; public matka (int x, int y) { this.x=x; this.y=y; } public void Paint (Graphics g) { //Rectangle r=new Rectangle(); g.fillRect(x, y, 200, 20); } [COLOR="#FF0000"]public void moveL(int dx){ this.x+=dx; } public void moveR(int dx){ this.x-=dx; }[/COLOR] }
And here my main page:
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.Timer; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;; public class BallWorld1 extends Frame { private Ball aBall; private matka aMatka; public static void main (String [ ] args) { BallWorld1 world = new BallWorld1 (Color.red); world.show (); } private BallWorld1 (Color ballColor) { // constructor for new ball world // resize our frame setSize (getHeight(),getWidth()); setTitle ("Ball World"); addMouseListener(new BallListener()); aMatka = new matka(740,980); // initialize object data field aBall = new Ball (10, 15, 5); aBall.setColor (ballColor); aBall.setMotion (3.0, 6.0); addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public void paint (Graphics g) { aMatka.Paint(g); aBall.paint (g); aBall.move(); if ((aBall.x() < 0) || (aBall.x() > getSize().width)) aBall.setMotion (-aBall.xMotion(), aBall.yMotion()); if ((aBall.y() < 0) || (aBall.y() > getSize().height)) aBall.setMotion (aBall.xMotion(), -aBall.yMotion()); try { Thread.sleep(100); } catch (InterruptedException e) {} repaint(); } class BallListener extends MouseAdapter { public void mousePressed(MouseEvent e) { aBall.moveTo(e.getX(), e.getY()); } } [COLOR="#FF0000"]class MatkaListener implements KeyListener { public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_RIGHT: aMatka.moveR(20); break; case KeyEvent.VK_LEFT: aMatka.moveL(20); break; } } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } }[/COLOR] }
Can you help me to see my problem and fix that ?