1

I followed an example someone posted on another question for key bindings to control an object. For the sake of simplicity all it is controlling is printing "woo" when VK_UP is pressed but it doesn't do that.

some code from here that I still can't manage to get working.

Heres the main

import javax.swing.*;

@SuppressWarnings("serial")
public class apples extends JFrame {

    static boolean running;

public static void main(String[] args){
    JFrame f = new JFrame();
    Peach p = new Peach();
    f.getContentPane().add(new test());
    f.add(new test());
    f.add(p);
    f.setSize(400,250);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
    p.run();
    }


}

and here is the key binding stuff

    import java.awt.*;
import java.awt.event.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;


@SuppressWarnings("serial")
public class Peach extends JPanel {

    public void paint(Graphics g){
        setOpaque(false);
        super.paintComponent(g);
        this.setBackground(Color.WHITE);

        g.setColor(Color.BLACK);
        g.fillOval(x, y, br, br);

        g.drawString("Sort of Pong?", 157, 20);

        g.setColor(Color.BLACK);
        g.fillRect(paddlex, paddley, psizex, psizey);

        //g.setColor(new Color(51, 255, 204));
        //g.fillRect(100, 100, 80, 100);
        repaint();
    }



public void Panel(){    Thread go = new Thread();
    go.start(); }

    int xpos;
    final int left = -1; //left increment
    final int right = 1; //right increment
    int up = -1; // up increment (negative because down is revered in coordinates)
    int down = 1; // down increment
    boolean check = true; // moving or not
    int x =200; // ball position x
    int y=100; // ball position y
    boolean rightmove = true; // moving right or left
    boolean leftmove = false; // moving left
    boolean upmove = true; // moving up
    boolean downmove = false; // moving down
    int paddlex = 100; // paddle position x
    int paddley = 100; // paddle position y
    int psizex = 100; // paddle size in x dimension 
    int psizey = 100; // paddles size in y dimension
    int cdy; // for checking other side for collisions
    int cdx; // for checking other side for collisions
    int br = 8; // ball radius
    boolean shipupmove = false;
    boolean shipdownmove = true;
    int shipspeed = 1;
    boolean goup;
    long counter = 0;

    public void calc(){
        cdy = psizey + paddley; // for checking other side for collisions
        cdx = psizex + paddlex; // for checking other side for collisions
    }

    public void run(){
        while(true){
            move();
            collisiond();
            calc();
            counter++;
            try
            {
            Thread.sleep(8);
            }
            catch(InterruptedException ex)
            {
                        }
        }
    }

    public void move(){
            if (rightmove){
                if(x <377){
                    x = (x+right);
                }else{rightmove = false; leftmove = true;}
            }
    if(leftmove)
        if(x > 0){                      
        x = (x-right);
        }else{rightmove = true; leftmove= false;}


    if (downmove){
        if(y <205){
            y = (y+down);
        }else{downmove = false; upmove = true;}
    }
    if(upmove)
            if(y > 0){                      
                y = (y+up);
        }else{downmove = true; upmove= false;}  

}

    public void collisiond(){
        if(leftmove && (x ==(cdx+1) || x == (cdx-1) || x == cdx)&& y >= paddley-br && y <= cdy){
            leftmove = false; rightmove = true;
        }
        if(rightmove && (x ==(paddlex-br+1) || x == (paddlex-br-1) || x == paddlex-br) && y >= paddley && y <= cdy){
            rightmove = false; leftmove = true;
        }
        if(upmove && ((y == cdy+1) || (y == cdy-1) || (y == cdy)) && x >= paddlex && x<= cdx){
            upmove = false; downmove = true;
        }
        if(downmove && ((y == paddley - br +1) || (y == paddley - br -1) || (y == paddley - br)) && x > paddlex && x < cdx){
            downmove = false; upmove = true;
        }
    }

    public void movepaddle(){
        if(shipupmove && paddley !=0){
            this.paddley = paddley - 1  ;
        }
        if (shipdownmove && paddley < (205-psizey)){
            this.paddley = paddley + 1;
        }
        if(paddley < 16){
            shipupmove = false; shipdownmove = true;
        }
        if(cdy > 189){
            shipupmove = true; shipdownmove = false;
        }
        repaint();


}
}
class test extends JPanel{

        private static final long serialVersionUID = 1L;
        private Map<Direction, Boolean> directionMap = new HashMap<Direction, Boolean>();
        int DELAY = 5;

        enum Direction {
            UP(KeyEvent.VK_UP,true),
            DOWN(KeyEvent.VK_DOWN, false);
            private int KeyCode;
            boolean moveing;



            Direction(int KeyCode, boolean moveing) {
                this.KeyCode = KeyCode;
                this.moveing = moveing;

            }

            public int getKeyCode(){
                return KeyCode;
            }
            public boolean moveing(){
                return moveing;
            }

        }

    public test(){

        for(Direction direction : Direction.values()){
        directionMap.put(direction, false);

        }
        setBindings();  
        Timer timer = new Timer(5, new TimerListener());
        timer.start();
    }   
    private void setBindings(){
        InputMap in = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap act = getActionMap();
        for(final Direction d : Direction.values()){
            KeyStroke press = KeyStroke.getKeyStroke(d.getKeyCode(), 0 ,false);
            KeyStroke rel = KeyStroke.getKeyStroke(d.getKeyCode(),0,true);
            in.put(press, "key pressed");
            in.put(rel, "key released");
            act.put(d.toString()+"pressed", new AbstractAction(){

                private static final long serialVersionUID = 1L;

                public void actionPerformed(ActionEvent e) {
                    directionMap.put(d, true);      
                }       
            });
            act.put(d.toString()+"released", new AbstractAction(){

                private static final long serialVersionUID = 1L;

                public void actionPerformed(ActionEvent e) {
                                directionMap.put(d, false);
                }
            });
        }

    }

public class TimerListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            for(Direction d : Direction.values()){
                if(directionMap.get(d)){
                    if(d.moveing()){
                        System.out.println("woo");
                    }
                }
            }

        }


    }


}

any insight would be appreciated thank you

Community
  • 1
  • 1
Apcragg
  • 133
  • 1
  • 7
  • 1
    What the heck is the Peach class? Where is the code for it? And do you know that by adding it to the JFrame's contentPane you'll cover up the component added prior. Also the apples (better, Apples) class shouldn't extend JFrame since it doesn't behave as a JFrame. Finally, please adhere to Java's naming conventions if you want others to be able to better understand your code. – Hovercraft Full Of Eels Apr 01 '13 at 02:24
  • By the way, some of that code looks like mine, or mine by way of mKorbel. Also you shouldn't add the test class *twice* to the JFrame. – Hovercraft Full Of Eels Apr 01 '13 at 02:28
  • Peach class was focused on a little animation with basic physics but it wasn't relevant so i didn't include it. I apologize for any naming errors, I will try to work on making it cleaner. – Apcragg Apr 01 '13 at 02:30
  • By leaving in your Peaches code in your code above, you made your code non-compilable for us out of the box. Please avoid this in the future. – Hovercraft Full Of Eels Apr 01 '13 at 02:31
  • I added the whole code for compiling's sake. – Apcragg Apr 01 '13 at 02:34
  • `some of that code looks like mine, or mine by way of mKorbel` Yes and that code worked. It always amazes me the people copy code, make changes to it and then complain when it doesn't work. – camickr Apr 01 '13 at 02:38
  • `any insight would be appreciated thank you`, Don't make changes to working code unless you have a reason to do so. Then you test it to make sure it still works. If it doesn't work then you undo the changes you made. Don't expect us to do debugging for you. – camickr Apr 01 '13 at 02:39
  • @user2230137, then your question should be "I made this change, why doesn't it work?" We should not have to waste time guessing what you changed. – camickr Apr 01 '13 at 02:42
  • 1
    By the way your paint() method is totally messed up. First of all you should be overriding paintComponent() not paint(). You should not change a components property (ie. setOpaque(), setBackground()) in the peinting method. And you definitely don't want to invoke repaint() in the method. Its time you read the [Swing tutorial](http://docs.oracle.com/javase/tutorial/uiswing/TOC.html). It has sections on how to do "Custom Painting" correctly as well as a section on Key Bindings. – camickr Apr 01 '13 at 02:50

1 Answers1

2

The "actionMapKey" Object assign to the InputMap MUST be the same you use in the ActionMap

For example...

in.put(press, "key pressed");
in.put(rel, "key released");
act.put("key pressed", new AbstractAction(){...}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366