ryhn
ryhn

Reputation: 15

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

I am trying to make a simple JAVA game where an object is coming toward another static object or character and if I press "space" button the static object will jump and avoid the collision. I was successful to make the first object moving but I couldn't make the static object jump or move. I tried using keyevent but it didn't work. So how can I make it work? Or can you point out what am I doing wrong in my 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);
    }

}

Upvotes: 0

Views: 85

Answers (1)

Maurice Perry
Maurice Perry

Reputation: 9648

Not sure what you're trying to do, but if you want to listen to key events, you must register a listener (in the constructor, for instance):

addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent evt) {
        ...
    }
);

Upvotes: 1

Related Questions