Results 1 to 15 of 15
  1. #1
    gib65 is offline Member
    Join Date
    Jun 2010
    Posts
    86
    Rep Power
    0

    Default Jbuttons stealing focus from other components

    I'm programming a video game in swing. I've got a KeyListener (called InputProcessor) that processes keyboard input in order to control the main character (i.e. pressing the arrow keys determines which direction he moves). Up until just recently, this has been working fine, but recently I added a couple buttons to the main Jframe, and now pressing the arrows keys has no effect on the main character. My first hunch is that the buttons are stealing the entire focus so that no input from the keyboard gets transferred to my GamePanel (i.e. the main panel in which the game takes place).

    Here's my code for the main JFrame:

    Java Code:
    package framecomponents;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    import java.awt.Color;
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    import java.awt.Dimension;
    import java.awt.Container;
    
    public class MazeManiaFrame extends JFrame {
    
        // panels
        private GamePanel   gamePanel  = null; // where game is played
        private EastPanel	eastPanel  = null; // where buttons are
        private SouthPanel  southPanel = null;
    
    /************************** CONSTRUCTOR **************************/
    
        public MazeManiaFrame() {
    
    	// setup frame properties
    	setTitle("Maze Mania");
    	setSize(800, 800);
    	setLocation(200, 50);
    	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    	Container container = getContentPane();
    	container.setLayout(new GridBagLayout());
    
    	// create panels
    	gamePanel 	  = new GamePanel(); // main panel where game is played
    	JPanel NWPanel    = new JPanel();
    	JPanel NorthPanel = new JPanel();
    	JPanel NEPanel    = new JPanel();
    	eastPanel  	  = new EastPanel(); // where buttons are
    	JPanel SEPanel    = new JPanel();
    	southPanel 	  = new SouthPanel();
    	JPanel SWPanel    = new JPanel();
    	JPanel WestPanel  = new JPanel();
    
    	// set their preferred size
    	NWPanel.setPreferredSize(new Dimension(50, 50));
    	NorthPanel.setPreferredSize(new Dimension(400, 50));
    	NEPanel.setPreferredSize(new Dimension(200, 50));
    	SEPanel.setPreferredSize(new Dimension(200, 50));
    	SWPanel.setPreferredSize(new Dimension(50, 50));
    	WestPanel.setPreferredSize(new Dimension(50, 400));
    
    	// add panels to main container with constraints
    	GridBagConstraints constraints = new GridBagConstraints();
    	constraints.gridx = 0;
    	constraints.gridy = 0;
    	container.add(NWPanel, constraints);
    	constraints.gridx = 1;
    	container.add(NorthPanel, constraints);
    	constraints.gridx = 2;
    	container.add(NEPanel, constraints);
    	constraints.gridy = 1;
    	container.add(eastPanel, constraints);
    	constraints.gridy = 2;
    	container.add(SEPanel, constraints);
    	constraints.gridx = 1;
    	container.add(southPanel, constraints);
    	constraints.gridx = 0;
    	container.add(SWPanel, constraints);
    	constraints.gridy = 1;
    	container.add(WestPanel, constraints);
    	constraints.gridx = 1;
    	container.add(gamePanel, constraints);
    
    	pack();
        }
    
    /************************** END CONSTRUCTOR **************************/
    
    
    /************************** ACCESSORS **************************/
    
    /*** GET ***/
    
        // get panels
        public GamePanel  getGamePanel()  {return gamePanel;}
        public SouthPanel getSouthPanel() {return southPanel;} 
        public EastPanel     getEastPanel()  {return eastPanel;} 
    
        // get panel components
        public ClockLabel getClockLabel() {return southPanel.getClockLabel();}
    
    /************************** END ACCESSORS **************************/
    
    }
    And here's EastPanel where the buttons are:

    Java Code:
    package framecomponents;
    
    import javax.swing.JPanel;
    import javax.swing.JButton;
    
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    import java.awt.Dimension;
    import java.awt.Insets;
    
    public class EastPanel extends JPanel {
    
        public EastPanel() {
    
    	setLayout(new GridBagLayout());
    	setPreferredSize(new Dimension(200, 400));
    	setOpaque(true);
    
    	JButton button1 = new JButton("button 1");
    	button1.setPreferredSize(new Dimension(150, 30));
    
    	JButton button2 = new JButton("button 2");
    	button2.setPreferredSize(new Dimension(150, 30));
    
    	GridBagConstraints constraints = new GridBagConstraints();
    	Insets insets = new Insets(0, 5, 2, 0);
    	constraints.insets = insets;
    
    	constraints.gridx = 0;
    	constraints.gridy = 0;
    	add(button1, constraints);
    
    	insets.top = 2;
    	constraints.gridy = 1;
    	add(button2, constraints);
        }
    }
    and here's my InputProcessor:

    Java Code:
    package game;
    
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.ActionEvent;
    
    import java.util.Date;
    
    public class InputProcessor implements KeyListener {
    
    
    /************************** EMBEDDED CLASS **************************/
    
        /* The TimedKeyEvent class is to be placed in the timedKeyEventArray (below)
         * and represents a key having been pressed.
         */
    
        private class TimedKeyEvent {
    
    	public long    time_stamp = -1;	   // when key was pressed
    	public boolean held_down  = false; // is it being held down?
    	public int     key_code   = -1;	   // which arrow key was it? (-1 = no key pressed)
    
    	public TimedKeyEvent(int kc, boolean hd) {
    
    	    key_code   = kc;
    	    held_down  = hd;
    	    time_stamp = new Date().getTime();
    	}
        }
    
    /************************** END EMBEDDED CLASS **************************/
    
    
        // key codes
        public static final int LEFT  = 37;
        public static final int UP    = 38;
        public static final int RIGHT = 39;
        public static final int DOWN  = 40;
    
        public static final int ARRAY_SIZE = 256;
    
        // array to hold TimedKeyEvents. To be placed at index = TimedKeyEvent.key_code.
        // To be indexed using index_array (in case above key codes aren't consecutive on some systems
        // helm points to oldest TimedKeyEvent (among the arrow keys)
    
        private TimedKeyEvent timedKeyEvents[] = new TimedKeyEvent[ARRAY_SIZE];
        private int 	  index_array[]    = {RIGHT, DOWN, LEFT, UP};
        private int 	  helm 		   = -1;
    
        // true when GameControl needs to be notified when an arrow key has been released (for enabling GoodGuy's movement)
        private boolean notify_on_key_release = false;
    
        private GameControl gameControl = null;
    
    
    /************************** CONSTRUCTOR **************************/
    
        public InputProcessor() {
    
    	// initialize all TimedKeyEvents to null
    	for (int i = 0; i < ARRAY_SIZE; i++)
    	    timedKeyEvents[i] = null;
        }
    
    /************************** END CONSTRUCTOR **************************/
    
    
    /************************** KEYEVENT METHODS **************************/
    
        // record KeyEvent (as a TimedKeyEvent) in array and update helm
        public void keyPressed(KeyEvent keyEvent) {
    
    	int kc = keyEvent.getKeyCode();
    	timedKeyEvents[kc] = new TimedKeyEvent(kc, true);
    	if (helm == -1) updateHelm();
        }
    
    /////////////
    
        // remove TimedKeyEvent from array and update helm
        public void keyReleased(KeyEvent keyEvent) {
    
    	int kc = keyEvent.getKeyCode();
    	timedKeyEvents[kc] = null;
    	if (helm == kc) updateHelm();
    
    	// notify GameControl that key has been released (in case GoodGuy's movements needs enabling)
    	if (notify_on_key_release) {
    	    if (gameControl.notify(keyEvent))
    	        notify_on_key_release = false; // only set to false if GoodGuy DID need enabling (depends on which key it was)
    	}
        }
    
    /////////////
    
        public void keyTyped(KeyEvent keyEvent) {}
    
    /************************** END KEYEVENT METHODS **************************/
    
    
    /************************** HELM CONTROL **************************/
    
        // updates helm to point at arraw key with oldest time stamp
        private void updateHelm() {
    
    	long oldest_time_stamp;
    
    	// helm = -1 means not pointing at any key
    	// figure out if an arrow key is held down and point to it (should be AT MOST one)
    	if (helm == -1) {
    
    	    if (timedKeyEvents[RIGHT] != null) helm = RIGHT;
    	    if (timedKeyEvents[DOWN]  != null) helm = DOWN;
    	    if (timedKeyEvents[LEFT]  != null) helm = LEFT;
    	    if (timedKeyEvents[UP]    != null) helm = UP;
    
    	// if hilm != -1, see if key it points at is null
    	// if so, find remaining arrow key with oldest time stamp
    	// initialize helm to -1 so that if no arrow keys found,
    	// it will remain at -1 indicating no arrow keys are down.
    
    	} else if (timedKeyEvents[helm] == null) {
    
    	    oldest_time_stamp = new Date().getTime();
    	    helm = -1;
    
    	    for (int i = 0; i < 4; i++)
    
    		if (timedKeyEvents[index_array[i]] != null &&
    		    timedKeyEvents[index_array[i]].time_stamp < oldest_time_stamp) {
    		    oldest_time_stamp = timedKeyEvents[index_array[i]].time_stamp;
    		    helm = index_array[i];
    		}
    	}
    
    	// if helm isn't pointing to null, no need to change it
        }
    
    /************************** END HELM CONTROL **************************/
    
    
    /************************** ACCESSORS **************************/
    
    /*** DOES/IS ***/
    
        public boolean doesRightHaveHelm() {
    
    	if (helm == RIGHT)
    	    return timedKeyEvents[helm].held_down;
    	else return false;
        }
    
    /////////////
    
        public boolean doesDownHaveHelm() {
    
    	if (helm == DOWN)
    	    return timedKeyEvents[helm].held_down;
    	else return false;
        }
    
    /////////////
    
        public boolean doesLeftHaveHelm() {
    
    	if (helm == LEFT)
    	    return timedKeyEvents[helm].held_down;
    	else return false;
        }
    
    /////////////
    
        public boolean doesUpHaveHelm() {
    
    	if (helm == UP)
    	    return timedKeyEvents[helm].held_down;
    	else return false;
        }
    
    /////////////
    
    // this might pose problems for key typed events (ex. when traversing ballchain)
        public boolean isArrowKeyPressed() {
    	
    	if (helm == RIGHT || helm == DOWN || helm == LEFT || helm == UP)
    	    return true;
    	return false;
        }
    
    /*** RESET ***/
    
        // to be used ONLY for reseting key typed events for arrow keys
        public void resetArrowKeyTyped() {
    
    	timedKeyEvents[helm] = null;
    	helm = -1;	
        }
    
    /*** SET ***/
    
        public void setGameControl(GameControl gameControl) {
    
    	if (gameControl == null) {
    	    System.out.println("gameControl is null in InputProcessor.setGameControl().");
    	}
    
    	this.gameControl = gameControl;
        }
    
    /////////////
    
        public void setNotifyOnKeyRelease() {notify_on_key_release = true;}
    
    /************************** END ACCESSORS **************************/
    
    }
    [/code]
    Last edited by gib65; 09-27-2010 at 12:42 AM.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  3. #3
    paul pasciak is offline Senior Member
    Join Date
    Jul 2008
    Posts
    125
    Rep Power
    0

    Default Make button return focus or disable

    I have scanned through your KeyListener code.
    I have not looked at it very carefully.

    Because you claim it worked, and I believe I
    found an external reference within your KeyListener
    named "gameControl", I assume it works.

    I agree that the buttons you have added are
    probably stealing the focus from your game.
    Here is how I have refocused them in some of
    my projects.

    1. Create an ActionListener for your buttons.
    2. In the default methods for the buttons, use
    requestFocusInWindow();

    (of course the default methods will have to
    reference the component you would like to
    gain the focus by some means, like:

    gameFrame.requestFocusInWindow();
    or
    gF.windowFrameView.requestFocusInWindow();
    etc.)

    Now when you press a button, it should redirect
    the focus to that particular component.

    Besides this process, I believe there is a
    Button method you can set in a Button object
    that will cause it to refuse focus.
    It's worth checking the API for this method.
    It will save you from implementing the
    ActionListener I have suggested.

    But you will eventually implement an ActionListener.

  4. #4
    gib65 is offline Member
    Join Date
    Jun 2010
    Posts
    86
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Use Key Binding not a KeyListener and if done correctly, you won't have this problem.
    I read up on how key bindings work (How to Use Key Bindings (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)) and based on what I read, I tried implementing this:

    Java Code:
    public GamePanel extends JPanel {
    
    // ...
    
    /************************** CONSTRUCTOR **************************/
    
        public GamePanel() {
    
    	setPreferredSize(new Dimension(width, height));
    	setBackground(Color.WHITE);
    	setOpaque(true);
    
    	getInputMap().put(KeyStroke.getKeyStroke("n"), "pressed");
    	getActionMap().put("pressed", new KeyActionListener());
        }
    
    /************************** END CONSTRUCTOR **************************/
    
    // ...
    
    }
    And I created a KeyActionListener class to perform the actions when keys are pressed (right now I have it set to react only to the 'n' key being pressed):

    Java Code:
    public class KeyActionListener extends AbstractAction {
    
        public KeyActionListener() {}
    
        public void actionPerformed(ActionEvent actionEvent) {
    
    	System.out.println("action performed");
        }
    }
    But when I run this, I don't get the message "action performed" I was expecting to get. Any guesses as to why?

    (I'm basing my implementation of the KeyActionListener on this: How to Use Actions (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)).

    Quote Originally Posted by paul pasciak
    I have scanned through your KeyListener code.
    I have not looked at it very carefully.

    Because you claim it worked, and I believe I
    found an external reference within your KeyListener
    named "gameControl", I assume it works.

    I agree that the buttons you have added are
    probably stealing the focus from your game.
    Here is how I have refocused them in some of
    my projects.

    1. Create an ActionListener for your buttons.
    2. In the default methods for the buttons, use
    requestFocusInWindow();

    (of course the default methods will have to
    reference the component you would like to
    gain the focus by some means, like:

    gameFrame.requestFocusInWindow();
    or
    gF.windowFrameView.requestFocusInWindow();
    etc.)

    Now when you press a button, it should redirect
    the focus to that particular component.

    Besides this process, I believe there is a
    Button method you can set in a Button object
    that will cause it to refuse focus.
    It's worth checking the API for this method.
    It will save you from implementing the
    ActionListener I have suggested.

    But you will eventually implement an ActionListener.
    I will try some of your suggestions out and report back.

    I have since added an actionPerformed() method to my EastPanel (a JPanel that contains the buttons).

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by gib65 View Post
    I read up on how key bindings work (How to Use Key Bindings (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)) and based on what I read, I tried implementing this:

    Java Code:
        public GamePanel() {
    	//....
    
    	getInputMap().put(KeyStroke.getKeyStroke("n"), "pressed");
    	getActionMap().put("pressed", new KeyActionListener());
        }
    
    // ...
    
    }
    And I created a KeyActionListener class to perform the actions when keys are pressed (right now I have it set to react only to the 'n' key being pressed):

    But when I run this, I don't get the message "action performed" I was expecting to get. Any guesses as to why?
    It may be that you're using the wrong input map. Try using the one associated with JComponent.WHEN_IN_FOCUSED_WINDOW, e.g.,

    Java Code:
        public GamePanel() {
    	//....
    
    	int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
    	getInputMap(condition).put(KeyStroke.getKeyStroke("n"), "pressed");
    	getActionMap().put("pressed", new KeyActionListener());
        }
    
    // ...
    
    }
    Also, I respectfully but strongly disagree with paul pasciak's recommendation. Again, use Key Binding. This is where they really shine.
    Last edited by Fubarable; 09-27-2010 at 09:55 PM. Reason: showed a code example

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    For one example of Key Binding with animation, please have a look at code I created for an earlier thread here: MoveIcon.java

  7. #7
    gib65 is offline Member
    Join Date
    Jun 2010
    Posts
    86
    Rep Power
    0

    Default

    Thanks Fubarable, but it's still not responding. I tried passing all three values into getInputMap(int). I had a look at your example but couldn't find anything significantly different from what I'm doing. Any other suggestions would be greatly appreciated.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by gib65 View Post
    Thanks Fubarable, but it's still not responding. I tried passing all three values into getInputMap(int). I had a look at your example but couldn't find anything significantly different from what I'm doing. Any other suggestions would be greatly appreciated.
    At this point, I'd suggest you create Short, Self Contained, Correct Example (SSCCE) and post it here: SSCCE. This is a small program that compiles, runs, demonstrates your problem, and contains no extraneous code. Please read the link, and have a go at it. Creating allows you to post a short program that we can inspect, run, test, and alter and help you solve your problem.

    This will take some effort on your part, but doing this will greatly increase your chances of our being able to help you in a timely manner.

    Best of luck!

  9. #9
    gib65 is offline Member
    Join Date
    Jun 2010
    Posts
    86
    Rep Power
    0

    Default

    Okay, here's my SSCCE. Thankfully, I was able to reproduce the error this time. Again, the problem is, I *think* I'm implementing key binding properly, but I'm not getting the message "action performed" that I'm expecting on pressing 'n'.

    I'm attaching the SSCCE and I'll also post it here:

    Main.java

    Java Code:
    import java.lang.Runnable;
    
    public class Main {
    
        public static void main(String[] args) {
    
    	javax.swing.SwingUtilities.invokeLater(new Runnable() {
    	    public void run() {new MyFrame();}
    	});
        }
    }
    MyFrame.java:

    Java Code:
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JComponent;
    import javax.swing.KeyStroke;
    
    import java.awt.Dimension;
    import java.awt.Container;
    
    public class MyFrame extends JFrame {
    
        public MyFrame() {
    
    	setTitle("MyFrame");
    	setLocation(200, 200);
    	setPreferredSize(new Dimension(200, 100));
    
    	JPanel panel = new JPanel();
    	JLabel label = new JLabel("hello world");
    
    	panel.add(label);
    	panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("n"), "pressed");
    	panel.getActionMap().put("pressed", new KeyActionListener());
    
    	Container container = getContentPane();
    	container.add(panel);
    
    	pack();
    	setVisible(true);	
        }
    }
    KeyActionListener.java:

    Java Code:
    import javax.swing.AbstractAction;
    
    import java.awt.event.ActionEvent;
    
    public class KeyActionListener extends AbstractAction {
    
        public KeyActionListener() {}
    
        public void actionPerformed(ActionEvent actionEvent) {
    
    	System.out.println("action performed");
        }
    }
    Attached Files Attached Files

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Yep, the SSCCE helps a lot. You're not getting your key strokes correctly. Try this:
    Java Code:
          JPanel panel = new JPanel();
          JLabel label = new JLabel("hello world");
    
          panel.add(label);
          panel.add(new JButton("Button")); // to steal focus
          panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_N, 0), "pressed");
          panel.getActionMap().put("pressed", new KeyActionListener());

    One very small nit-pick. To make the SSCCE even easier, put all the code into one file like so:
    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.Runnable;
    
    public class Gib65Main {
    
       public static void main(String[] args) {
    
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                new MyFrame();
             }
          });
       }
    }
    
    class MyFrame extends JFrame {
    
       public MyFrame() {
    
          setTitle("MyFrame");
          setLocation(200, 200);
          setPreferredSize(new Dimension(200, 100));
    
          JPanel panel = new JPanel();
          JLabel label = new JLabel("hello world");
    
          panel.add(label);
          panel.add(new JButton("Button"));
          panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_N, 0),
                   "pressed");
          panel.getActionMap().put("pressed", new KeyActionListener());
    
          Container container = getContentPane();
          container.add(panel);
    
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          pack();
          setVisible(true);
       }
    }
    
    class KeyActionListener extends AbstractAction {
    
       public KeyActionListener() {
       }
    
       public void actionPerformed(ActionEvent actionEvent) {
    
          System.out.println("action performed");
       }
    }
    :)

  11. #11
    gib65 is offline Member
    Join Date
    Jun 2010
    Posts
    86
    Rep Power
    0

    Default

    Thanks Fubarable,

    BTW, what does the VK stand for?

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by gib65 View Post
    Thanks Fubarable,
    You're welcome!


    BTW, what does the VK stand for?
    Check out the KeyEvent section of the API for a list of these constants and the answer to your question: "virtual key"

  13. #13
    gib65 is offline Member
    Join Date
    Jun 2010
    Posts
    86
    Rep Power
    0

    Default

    Okay, thanks again Fubarable,

    I'm going to ask one more question and then mark this thread 'solved'.

    If I've got a whole series of key bindings, how do I distinguish between them in the actionPerformed method.

    I set up a bindKeys() method in my GamePanel that looks like this:

    Java Code:
        public void bindKeys(InputProcessor inputProcessor) {
    
    	int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
    	InputMap inputMap = getInputMap(condition);
    	ActionMap actionMap = getActionMap();
    
    	// up arrow key
    	inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "pressed");
    	actionMap.put("pressed", inputProcessor);
    	inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "released");
    	actionMap.put("released", inputProcessor);	
    
    	// right arrow key
    	inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "pressed");
    	actionMap.put("pressed", inputProcessor);
    	inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "released");
    	actionMap.put("released", inputProcessor);
    
    	// down arrow key
    	inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "pressed");
    	actionMap.put("pressed", inputProcessor);
    	inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "released");
    	actionMap.put("released", inputProcessor);
    
    	// left arrow key
    	inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "pressed");
    	actionMap.put("pressed", inputProcessor);
    	inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "released");
    	actionMap.put("released", inputProcessor);
        }
    and in my InputProcessor class, the actionPerformed method looks like this:

    Java Code:
        public void actionPerformed(ActionEvent actionEvent) {
    
    	System.out.println("action performed");
    	System.out.println("action command: " + actionEvent.getActionCommand());
    	System.out.println("modifier: " + actionEvent.getModifiers());
    	System.out.println("parameter string: " + actionEvent.paramString());
    	System.out.println("ID: " + actionEvent.getID());
    
    	if (actionEvent.getSource() == gameControl.getMazeManiaFrame().getGamePanel())
    	    System.out.println("source is gamePanel");
    	else System.out.println("source is NOT gamePanel");
        }
    In other words, I have it printing out all the information an ActionEvent has available, but I can't see anything that would tell me which key binding it is associated with (for example, whether it was "pressed" or "release" or whether it was the down arrow or the up arrow, etc.).

    How would you go about figuring this information out? Would you create a separate InputProcessor for each and every key binding (I'd need some static variables in that case since there are some variables they need to share).

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  15. #15
    gib65 is offline Member
    Join Date
    Jun 2010
    Posts
    86
    Rep Power
    0

    Default

    So let me see if I understand this correctly.

    Java Code:
    81.  private void setKeyBindings() {
    82.    InputMap inMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    83.    ActionMap actMap = getActionMap();
    84. 
    85.    for (final Direction direction : Direction.values()) {
    86.      KeyStroke pressed = KeyStroke.getKeyStroke(direction.getKeyCode(), 0,
    87.          false);
    88.      KeyStroke released = KeyStroke.getKeyStroke(direction.getKeyCode(), 0,
    89.          true);
    90. 
    91.      inMap.put(pressed, direction.toString() + "pressed");
    92.      inMap.put(released, direction.toString() + "released");
    93. 
    94.      actMap.put(direction.toString() + "pressed", new AbstractAction() {
    95.        public void actionPerformed(ActionEvent e) {
    96.          directionMap.put(direction, true);
    97.        }
    98.      });
    99.      actMap.put(direction.toString() + "released", new AbstractAction() {
    100.        public void actionPerformed(ActionEvent e) {
    101.          directionMap.put(direction, false);
    102.        }
    103.      });
    104.    }
    105. 
    106.  }
    You have a HashMap that you call DirectionMap. This is where you keep track of which arrows key are pressed/released (using boolean values).

    When you bind an Action object to a key in your ActionMap, that Action object is a new one for every direction.

    Essentially, this seems like what I was suggesting. Your DirectionMap would be the equivalent to the static variables I suggested (i.e. all instances of AbstractAction share it). Is this what you recommend I do?

Similar Threads

  1. How to get focus on components in LWUIT form
    By Basit781 in forum CLDC and MIDP
    Replies: 5
    Last Post: 05-21-2010, 08:41 AM
  2. Help with JButtons...
    By ashton in forum New To Java
    Replies: 8
    Last Post: 01-26-2009, 09:38 AM
  3. JButtons
    By jadaleus in forum Advanced Java
    Replies: 4
    Last Post: 10-17-2008, 02:49 AM
  4. 2D Array of JButtons
    By stevemcc in forum AWT / Swing
    Replies: 1
    Last Post: 02-16-2008, 11:42 PM
  5. JButtons
    By fgasimzade in forum SWT / JFace
    Replies: 1
    Last Post: 12-25-2007, 05:39 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •