java - How to handle two different objects in the same JPanel at the same time? -


i trying make simple java game object coming toward static object or character , if press "space" button static object jump , avoid collision. successful make first object moving couldn't make static object jump or move. tried using keyevent didn't work. how can make work? or can point out doing wrong in code?

package jpanel;  import java.awt.*; import javax.swing.*; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.awt.event.keyevent;  public class jp extends jpanel implements actionlistener{     timer t;     int x,y,k;     jp(){         x=650;         k=0;         t=new timer(5,this);         t.start();     }     public void actionperformed(actionevent e){         x--;         //k++;         if(x==76){             x=650;         }         repaint();     }       public void keypressed(keyevent e){         int key=e.getkeycode();             if(key == keyevent.vk_space){                 k++;                /* if(k>300){                     k=0;                 }*/                 repaint();             }         }      public void paintcomponent(graphics g){         super.paintcomponent(g);         this.setbackground(color.black);         g.setcolor(color.blue);         g.fillrect(x,400,50,50);//moving object         g.setcolor(color.red);         //static object         g.fillrect(30, 350-k, 45, 70);//static_body         g.setcolor(color.yellow);         g.filloval(28, 310-k, 40, 40);//static_head         g.setcolor(color.green);         g.fillrect(30, 420-k, 10, 35);//static_leg1         g.fillrect(65, 420-k, 10, 35);//static_leg2         g.setcolor(color.blue);         g.fillrect(35, 350-k, 10, 45);//static_hand         g.setcolor(color.black);         g.filloval(55, 320-k, 7, 7);//static_eye     } }  public class jpanel extends jframe {       public static void main(string[] args) {         jp p=new jp();          jframe j=new jframe("test_case-1");         j.add(p);         j.setdefaultcloseoperation(jframe.exit_on_close);         j.setsize(700,500);         j.setvisible(true);     }  } 

not sure you're trying do, if want listen key events, must register listener (in constructor, instance):

addkeylistener(new keyadapter() {     public void keypressed(keyevent evt) {         ...     } ); 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -