الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

Moving Object

مغلق
بدأه المبرمج1 في 28 مارس 2004 · 16 رد · 1,107 مشاهدة · في JavaSE
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

in the following code you can move an object using keyBoard arrores

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class GUITest extends JFrame implements KeyListener {

  //private Container container;
  private Icon icon[] = { new ImageIcon("L1.gif"),//Left   <--- set an image here
                          new ImageIcon("R1.gif"),//Right  <--- set an image here
                          new ImageIcon("U1.gif"),//Up     <--- set an image here
                          new ImageIcon("D1.gif")};//Down  <--- set an image here

  private Point ObjectLocation,LabelLocation,FrameSize;
  private JLabel label;
  int counter;
  int KeyCode;
  int IconNumber;

  //constructor-----------------------------------------------------------------
  public GUITest()
  {
  super("move the object");

  // the fram size
  FrameSize = new Point();
  FrameSize.x = 300;
  FrameSize.y = 200;

  // the object location
  LabelLocation = new Point();
  ObjectLocation = new Point();

  // set the default icon
  label = new JLabel(icon[0]);
  getContentPane().add(label);

  IconNumber=0;

  // add key lisitener
  addKeyListener(this);

  // the fram setting
  setSize(FrameSize.x ,FrameSize.y);
  setVisible(true);
  getContentPane().setBackground(Color.white);

  }// end constructor

  //
  // start the key listening
  // keyPressed-----------------------------------------------------------------
  public void keyPressed(KeyEvent event)
  {
    KeyCode = event.getKeyCode();
    moveObject(KeyCode);
  }

  // keyReleased----------------------------------------------------------------
  public void keyReleased(KeyEvent event)
  {
  }

  // keyTyped-------------------------------------------------------------------
  public void keyTyped(KeyEvent event)
  {
  }

  // the method that will move the object---------------------------------------
  public void moveObject(int KeyCode)
  {
   //the step size
   int StepSize = 10;
   int XStepSize=0, YStepSize=0;

   LabelToFrame(ObjectLocation);
   LabelLocation.setLocation(ObjectLocation);
   // the index number of the icon


   switch(KeyCode)
     {
       //left key
       case 37:
         XStepSize  = -1;
         YStepSize  = 0;
         IconNumber = 0;
         break;
       //right key
       case 39:
         XStepSize  = 1;
         YStepSize  = 0;
         IconNumber = 1;
         break;
       //Up key
       case 38:
         XStepSize  = 0;
         YStepSize  = -1;
         IconNumber = 2;
         break;
       //Down key
       case 40:
         XStepSize  = 0;
         YStepSize  = 1;
         IconNumber = 3;
         break;
       //defult
       default:
          break;
     }//end switch

     //withen the frame is resize
     FrameSize.x = getContentPane().getWidth();
     FrameSize.y = getContentPane().getHeight();

     // inside the X-coordenat limit
     LabelLocation.x += StepSize * XStepSize;
     if( (LabelLocation.x >= 10 && LabelLocation.x <= FrameSize.x-10))
      {ObjectLocation.x = LabelLocation.x;}
      else if(LabelLocation.x >= FrameSize.x-10){LabelLocation.x = FrameSize.x-11;}
      else {LabelLocation.x = 11;}
      ObjectLocation.x = LabelLocation.x;

      // inside the Y-coordenat limit
      LabelLocation.y += StepSize * YStepSize;
      if( (LabelLocation.y >= 10 && LabelLocation.y <= FrameSize.y-10))
       {ObjectLocation.y = LabelLocation.y;}
       else if(LabelLocation.y >= FrameSize.y-10){LabelLocation.y = FrameSize.y-11;}
       else {LabelLocation.y = 11;}
       ObjectLocation.y = LabelLocation.y;

      frameToLabel(ObjectLocation);
      label.setIcon(icon[IconNumber]);
      label.setLocation(ObjectLocation);

  }// end method moveObject

  //chnage from Fram cordinate to Label cordinate
  private void frameToLabel(Point ObjectLocation)
  {
        ObjectLocation.x -= FrameSize.x/2;
        ObjectLocation.y -= FrameSize.y/2;
  }

  //chnage from Label  cordinate to Fram cordinate
  private void LabelToFrame(Point ObjectLocation)
  {
        ObjectLocation.x += FrameSize.x/2;
        ObjectLocation.y += FrameSize.y/2;
  }

  public static void main(String[] args) {
    System.out.println("\n\n\tStart the main Method:\n");

   // the call for the classes start from hear ---VV--V--Vv ----vV-------------

   //GUITest test = new GUITest();
   GUITest test = new GUITest();
   test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   // the call for the classes end hear ------------^^-^^^---^-^^^^^-----------

 }//end the main method


}// end class

and if you face some diffeculty in the code , i will be hape to answer...

#2

can you explain more what does this prog do ???

لماذا تكون الليغو اللعبة الأكثر عبقرية في العالم؟

لأنها غير قابلة للتجزئة ، وتختلف فيما بينها بالألوان و الأشكال ، وتمتلك القدرة على تكوين علاقات مع بعض. نستطيع أن نقول أن أجزاء الليغو أبدية. وهي تشبه الذرات في تراكيبها للكون

-----

وائل بن أحمد كابلي

مستشار تطوير برمجيات | مايكروسوفت للخدمات الاستشارية

MCSE | MCTS SharePoint Infrastructure | MCTS SharePoint - Development | MCP | MSF Essentials

http://blogs.msdn.com/wael

@waelkabli

#3

the program is simple...

if you run it you will see an object , this object is a *.gif image..

if you press any arrow button the image will go with the direction of the arrow , and for each direction there is diffrent shape ,

the objet of teh programm is to know how liseten to Key Press, and move an object arround the fram ..

just run the appliction and you will note what it doing, and if any thing wrong inform me

#4

اعتقد ان هناك خطا في هذا الكود

الذي يظهر لي صورة واحده من الاربع صور

ولا يظهر لي اي تكست فيلد

لا دري هل الخطأ من عندي ام ان هناك من يشاركني في هذا

#5

there is no textField , ..

and use the key bord to move the objects ..

about the objeects images ... check that the images names match the code names..

and then inform me.

#6

هل من الممكن إرفاق الصور المستخدمه في البرنامج

شكرًا مقدمًا

#7

any image can be used in this programm

the most important thing , is that the name of the image must be the same exactly as the name in the code

and i used the picture:

icon11.gif

but with four refliction ... up down right and left ...

تم تعديل هذه المشاركة بواسطة المبرمج1 في 3 أبريل 2004 في 16:16

#8

Good Stuff!!!

I was doing the same thing one day (I was trying to making a game actually) and one question pop up.

can u make movement smoother? I mean showing more than one move for each key strike. I tried calling revalidate() and repaint() and non of them worked. Do u have any idea?!!

#9

based on my undersranding ...

this is the code

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Key extends JFrame implements KeyListener {

  //private Container container;
  private Icon icon[] = { new ImageIcon("L1.gif"),new ImageIcon("L2.gif"),//Left
                          new ImageIcon("R1.gif"),new ImageIcon("R2.gif"),//Right
                          new ImageIcon("U1.gif"),new ImageIcon("U2.gif"),//Up
                          new ImageIcon("D1.gif"),new ImageIcon("D2.gif")};//Down

  private Point ObjectLocation,LabelLocation,FrameSize;
  private JLabel label;
  int counter;
  int KeyCode;
  int IconNumber;

  //constructor-----------------------------------------------------------------
  public Key()
  {
  super("move the object");

  // the fram size
  FrameSize = new Point();
  FrameSize.x = 300;
  FrameSize.y = 200;

  // the object location
  LabelLocation = new Point();
  ObjectLocation = new Point();

  // set the default icon
  label = new JLabel(icon[0]);
  getContentPane().add(label);

  // the icon index number
  IconNumber=0;

  //set value
  counter=0;

  // add key lisitener
  addKeyListener(this);

  // the fram setting
  setSize(FrameSize.x ,FrameSize.y);
  setVisible(true);
  getContentPane().setBackground(Color.white);

  }// end constructor

  //
  // start the key listening
  // keyPressed-----------------------------------------------------------------
  public void keyPressed(KeyEvent event)
  {
    KeyCode = event.getKeyCode();
    moveObject(KeyCode);
    counter++;
  }

  // keyReleased----------------------------------------------------------------
  public void keyReleased(KeyEvent event)
  {
  }

  // keyTyped-------------------------------------------------------------------
  public void keyTyped(KeyEvent event)
  {
  }

  // the method that will move the object---------------------------------------
  public void moveObject(int KeyCode)
  {
   //the step size
   int StepSize = 10;
   int XStepSize=0, YStepSize=0;

   LabelToFrame(ObjectLocation);
   LabelLocation.setLocation(ObjectLocation);
   // the index number of the icon


   switch(KeyCode)
     {
       //left key
       case 37:
         XStepSize  = -1;
         YStepSize  = 0;
         IconNumber = 0;
         break;
       //right key
       case 39:
         XStepSize  = 1;
         YStepSize  = 0;
         IconNumber = 2;
         break;
       //Up key
       case 38:
         XStepSize  = 0;
         YStepSize  = -1;
         IconNumber = 4;
         break;
       //Down key
       case 40:
         XStepSize  = 0;
         YStepSize  = 1;
         IconNumber = 6;
         break;
       //defult
       default:
          break;
     }//end switch

     //withen the frame is resize
     FrameSize.x = getContentPane().getWidth();
     FrameSize.y = getContentPane().getHeight();
     //System.out.print("\nObjectLocation.x="+ObjectLocation.x+", ObjectLocation.y="+ObjectLocation.y);

     // inside the X-coordenat limit
     LabelLocation.x += StepSize * XStepSize;
     if( (LabelLocation.x >= 10 && LabelLocation.x <= FrameSize.x-10))
      {ObjectLocation.x = LabelLocation.x;}
      else if(LabelLocation.x >= FrameSize.x-10){LabelLocation.x = FrameSize.x-11;}
      else {LabelLocation.x = 11;}
      ObjectLocation.x = LabelLocation.x;

      // inside the Y-coordenat limit
      LabelLocation.y += StepSize * YStepSize;
      if( (LabelLocation.y >= 10 && LabelLocation.y <= FrameSize.y-10))
       {ObjectLocation.y = LabelLocation.y;}
       else if(LabelLocation.y >= FrameSize.y-10){LabelLocation.y = FrameSize.y-11;}
       else {LabelLocation.y = 11;}
       ObjectLocation.y = LabelLocation.y;

      // set the icon
      frameToLabel(ObjectLocation);
          //change to color of icon
          if(counter>1){changeIcon(); counter = 0;}
      label.setIcon(icon[IconNumber]);
      label.setLocation(ObjectLocation);


  }// end method moveObject

  //chnage from Fram cordinate to Label cordinate
  private void frameToLabel(Point ObjectLocation)
  {
        ObjectLocation.x -= FrameSize.x/2;
        ObjectLocation.y -= FrameSize.y/2;
  }

  //chnage from Label  cordinate to Fram cordinate
  private void LabelToFrame(Point ObjectLocation)
  {
        ObjectLocation.x += FrameSize.x/2;
        ObjectLocation.y += FrameSize.y/2;
  }

  // change icon while moving
  public void changeIcon ()
  {
    if(IconNumber %2 == 0) {IconNumber ++;}
    else IconNumber --;
  }

}// end class

and if there any doubt in the code ... just ask

تم تعديل هذه المشاركة بواسطة المبرمج1 في 4 أبريل 2004 في 09:01

#10

main البرنامج لا يحتوي على

وObject لايتحرك ولكن في كل محاولة للتحريك يظهر وميض blinking.

اعتقد انه لا مفر من الرسم البطيئ إلا بإستخدام void paint.

شكرًا جزيلاً على تفاعلك

#11

for the main problem ...

just add the code

public static void main(String[] args) {
   System.out.println("\n\n\tStart the main Method:\n");

  // the call for the classes start from hear ---VV--V--Vv ----vV-------------

  //Key test = new Key ();
  Key test = new Key ();
  test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  // the call for the classes end hear ------------^^-^^^---^-^^^^^-----------

}//end the main method

to the previous code ... and it will work ..

and about blanking ... i think that there is a problem in the image file names ..

try that and inform me

#12

thank you

now its working

and nice job man

لماذا تكون الليغو اللعبة الأكثر عبقرية في العالم؟

لأنها غير قابلة للتجزئة ، وتختلف فيما بينها بالألوان و الأشكال ، وتمتلك القدرة على تكوين علاقات مع بعض. نستطيع أن نقول أن أجزاء الليغو أبدية. وهي تشبه الذرات في تراكيبها للكون

-----

وائل بن أحمد كابلي

مستشار تطوير برمجيات | مايكروسوفت للخدمات الاستشارية

MCSE | MCTS SharePoint Infrastructure | MCTS SharePoint - Development | MCP | MSF Essentials

http://blogs.msdn.com/wael

@waelkabli

#13

i am happy that you like it MEMONONO

:)

#14

Yeah, u were right about the file name problem. The code works just fine. But as I said earlier, the movement isn't smooth.

I worked on that and this is what I got...

hopefully you will notice the difference.

/*
 * code2263
 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;

public class AnimatedKeyResponse extends JFrame implements KeyListener{
    ImageIcon[] images;
    int x=200,
        y=150,
        img=0;
    AnimatedBox box;
    /** Creates a new instance of AnimatedKeyResponse */
    public AnimatedKeyResponse() {
        images=new ImageIcon[]{
        new ImageIcon(getClass().getResource("D1.gif")),
        new ImageIcon(getClass().getResource("U1.gif")),
        new ImageIcon(getClass().getResource("L1.gif")),
        new ImageIcon(getClass().getResource("R1.gif"))};
        box=new AnimatedBox(this);
        getContentPane().add(box);
        addKeyListener(this);
        setSize(400, 300);
    }
    
    public static void main(String[] args){
        AnimatedKeyResponse window= new AnimatedKeyResponse();
        window.setVisible(true);
        window.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    
    
    public void keyPressed(KeyEvent e) {
        //JOptionPane.showMessageDialog(this,"hello");
        final int code=e.getKeyCode();
        Thread thrd=new Thread(new Runnable(){
            public void run(){
                move(code);
            }
        });
        thrd.start();
    }
    
    public void keyReleased(KeyEvent e) {
    }
    
    public void keyTyped(KeyEvent e) {

    }
    
    public void move(int code){
        int counter=20;
        int vVel=0, //vertical Velocity
            hVel=0; //horisantal Velocity
        
        switch(code){
            case 37://left
                hVel=-1;
                img=2;
                break;
            case 39://right
                hVel=1;
                img=3;
                break;
            case 38://up
                vVel=-1;
                img=1;
                break;
            case 40://down
                vVel=1;
                img=0;
                break;
        }
        while(0<counter--){
            x+=(x+hVel+images[0].getIconWidth()>box.getWidth() || x+hVel<0)? 
                            0 : hVel;
            y+=(y+vVel+images[0].getIconHeight()>box.getHeight() || y+vVel<0)?
                            0:vVel;
            box.repaint();
            try{
                Thread.sleep(10);
            }catch(Exception e){}
        }
    }
    private class AnimatedBox extends JPanel{
        public AnimatedBox(KeyListener window){
            //addKeyListener(window);
        }
        public void paint(Graphics g){
            g.clearRect(0,0, getWidth(),getHeight());
            g.drawImage(images[img].getImage(),x,y,(java.awt.image.ImageObserver)this);
        }
    }
}

Thank you for ur responses, you are really a good programmer.

If you have any questions about the code I'll be happy to answer.

AKR.jar

#15

To tell the troth your code is better than mines …. The object in your code is moving in smooth way …

thanks ..

but there a small problem ... the code did not work untill i had did a slight modification ...

i changed :

images= new ImageIcon[]{
       new ImageIcon(getClass().getResource("D1.gif")),
       new ImageIcon(getClass().getResource("U1.gif")),
       new ImageIcon(getClass().getResource("L1.gif")),
       new ImageIcon(getClass().getResource("R1.gif"))};

with :

images= new ImageIcon[]{
       new ImageIcon("D1.gif"),
       new ImageIcon("U1.gif"),
       new ImageIcon("L1.gif"),
       new ImageIcon("R1.gif")};

then the code work ... so why do you think that the code did not work in my PC

thanks again :)

تم تعديل هذه المشاركة بواسطة المبرمج1 في 7 أبريل 2004 في 12:38

#16

هذه الطريقة هي الأسلم ليعمل الكود في الحالتين

1- باستخدام طريقة Classes كلها مجمعه في مجلد واحد

2- تجميع الملفات في أرشيف مثل ملفات الjar و zip.

بالتأكيد عندما تصمم برنامج لأحدٍ ما سوف تقوم بتسليم ملف واحد يحتوي كل شيء بدلآ من تسليم عده ملفات( *.class و *.jpg و *.wav.....إلخ).

هذه الطريقة موازيه لملفات التطبيق *.exe اللتي يمكن انتاجها بالفيجول بيسك.

أضف إلى ذلك يمكنك تشغيل البرامج بالضغط المزدوج ولا حاجه إلى تشغيلcommand window لإدخال الأوامر.

لتوضيح الفكره سأعطيك هذا المثال

لنفترض ان البرنامج مقسم على الشكل الأتي

c:\
 |--myJava
 |     |--myProgram1
 |     |         |-myClass1.java
 |     |         |-myClass1.class
 |     |-myProgram1.jar
 |     |        
 |     |--myProgram2
 | 
 |--WINDOWS

الطريقة الوحيده لتشغيله بالطريقة التقليديه ( على حسب علمي) هي:

cd myJava/myProgram1
java myClass1

ولا يمكن برمجة نظام التشغيل ويندوز لتأدية هذه العمليه بسهوله

ولكن لو اضفت السطر التالي إلى myClass1.java

package myProgram1;

ومن ثم قمت بإنشاء الmyProgram1.jar بالطريقة الصحيحه لتشغيل البرنامج ما عليك إلا كتابة

java -jar c:\myJava\myProgram1.jar

اتمنى ان تتفق معي على ان هذه الطريقة هي الأسهل. على إية حال, لا يمكن ان تقرأ أي ملف من الأرشيف بهذه الطريقة

new ImageIcon("D1.gif"),

والطريقة الصحيحه هي

new ImageIcon(getClass().getResource("D1.gif")),

وهذا ينطبق على ملفات الصوت والصوره وكل شيء

لا أعرف لماذا لا يعمل البرنامج معك لأنه يعمل معي بشكل صحيح في الحالتين

انا استخدم j2sdk1.4.2

جرب استيراد الحزمه java.net.*

import java.net.*

وإن شاء الله يشتغل معك

اتمنى اني أكون افدت

#17

thank you ... i will see it and i will inform you ..

have a nice week end .... all of ArabTeam members

;)

هذا الموضوع مغلق.

مواضيع مشابهة