Results 1 to 9 of 9
  1. #1
    StaticFlow is offline Member
    Join Date
    May 2012
    Posts
    17
    Rep Power
    0

    Default KeyPress event controlling wrong component in JFrame

    Alright so my problem is that i have two components in my jFrame a custom JPanel that has a grid with a user controlled square in it the other is a tabbed frame that has multiple panels for user interaction. The custom JPanel has a keyPress event that when fired moves the square in the direction of the arrow key the user pressed, but what is happening instead is that it is just switching tabs on the tabbed frame at the bottom. I assume it has something to do with focus but i may be wrong. What im wondering is how do i make the KeyPress control my Jpanel and not the tabbed frame. here is my code:

    Grid Class:
    Java Code:
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class Grid extends JPanel implements KeyListener
    {
    	private Cell[][] cells;
    	private int lastKeyPressed;
    	private JPanel gameFrame = new JPanel();
    	public Grid(int numRows, int numCols)
    	{
    		init(numRows, numCols);
    	}
    
    	private void init(int numRows, int numCols)
    	{
                    lastKeyPressed = -1;
    		cells = new Cell[numRows][numCols];
    		for (int row = 0; row < numRows; row++)
    		{
    			for (int col = 0; col < numCols; col++)
    				cells[row][col] = new Cell();
    		}		
                    gameFrame.addKeyListener(this);
    		int cellSize = Math.max(Math.min(500 / numRows, 500 / numCols), 1);    
    		setPreferredSize(new Dimension(cellSize * numCols, cellSize * numRows));
    		gameFrame.add(this);
    	}
    
    	public void keyPressed(KeyEvent e)
    	{
    		lastKeyPressed = e.getKeyCode();
    		handleKeyPress(lastKeyPressed);
    	}
    	public void handleKeyPress(int keyPressed)
    	{
    		int key = keyPressed;
    		if(key == 38)// up
    		{
                          System.out.println("up");
    		}
    		else if(key == 40)//down
    		{
                          System.out.println("Down");
    		}
    		else if(key == 37)//left
    		{
                          System.out.println("left");
    		}
    		else if(key == 39)//right
    		{
                          System.out.println("right");
    		}
    	}
    }
    GameWindow class:
    Java Code:
    public class GameWindow extends JFrame {
    
    	private JPanel contentPane;
    	private Grid world;
    
    	/**
    	 * Launch the application.
    	 */
    	public static void main(String[] args) {
    		EventQueue.invokeLater(new Runnable() {
    			public void run() {
    				try{
    					play();					
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    
    		});
    	}
    private static void play() {			
    		GameWindow frame = new GameWindow();
    		frame.setVisible(true);
    
    	}
    
    
    
    
    	/**
    	 * Create the frame.
    	 */	
    	public GameWindow() {
    		//generate the ui
    		world = new Grid(25,43);
    		world.addKeyListener(new KeyAdapter() {
    			@Override
    			public void keyPressed(KeyEvent e) {
    				world.handleKeyPress();
    			}
    		});
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setBounds(700, 700, 750, 700);
    		contentPane = new JPanel();
    		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    		setContentPane(contentPane);
    		GridBagLayout gbl_contentPane = new GridBagLayout();
    		gbl_contentPane.columnWidths = new int[]{243, 0, 0};
    		gbl_contentPane.rowHeights = new int[]{433, 0, 0};
    		gbl_contentPane.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
    		gbl_contentPane.rowWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
    		contentPane.setLayout(gbl_contentPane);
    		JPanel gameAreaView =world;
    		GridBagConstraints gbc_gameAreaView = new GridBagConstraints();
    		gbc_gameAreaView.gridwidth = 2;
    		gbc_gameAreaView.insets = new Insets(0, 0, 5, 0);
    		gbc_gameAreaView.anchor = GridBagConstraints.NORTH;
    		gbc_gameAreaView.fill = GridBagConstraints.BOTH;
    		gbc_gameAreaView.gridx = 0;
    		gbc_gameAreaView.gridy = 0;
    		contentPane.add(gameAreaView, gbc_gameAreaView);
    		gameAreaView.setLayout(new GridLayout(1, 1, 0, 0));
    		JPanel UserMenu = new JPanel();
    		GridBagConstraints gbc_UserMenu = new GridBagConstraints();
    		gbc_UserMenu.fill = GridBagConstraints.BOTH;
    		gbc_UserMenu.gridx = 1;
    		gbc_UserMenu.gridy = 1;
    		contentPane.add(UserMenu, gbc_UserMenu);
    		UserMenu.setLayout(new GridLayout(0, 1, 0, 0));
    
    		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    		UserMenu.add(tabbedPane);
    
    		JPanel abilities = new JPanel();
    		tabbedPane.addTab("Abilities", null, abilities, null);
    
    		JPanel quests = new JPanel();
    		tabbedPane.addTab("Quests", null, quests, null);
    
    		JPanel inventory = new JPanel();
    		tabbedPane.addTab("Inventory", null, inventory, null);
    
    		JPanel Stats = new JPanel();
    		tabbedPane.addTab("Stats", null, Stats, null);
    	}
    
    }
    Cell class:
    Java Code:
    public class Cell //needed for Grid class but empty because contents not needed
    {
    	public Cell()
    	{
    
            }
    }

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

    Default Re: KeyPress event controlling wrong component in JFrame

    Your posted code doesn't compile for us, and if it did, your code does not reproduce your problem.

  3. #3
    StaticFlow is offline Member
    Join Date
    May 2012
    Posts
    17
    Rep Power
    0

    Default Re: KeyPress event controlling wrong component in JFrame

    im sorry, i missed the import statements for GameWindow, but how does it not reproduce my problem when i run that code above and try to use the arrow keys to trigger the println statements showing its coming from the right component it does not work. That is my problem.

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

    Default Re: KeyPress event controlling wrong component in JFrame

    Yes, it's a focus issue. You need to assign the focus to somewhere else, anywhere else. I'd use key bindings though over KeyListeners. For e.g.,

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    
    import javax.swing.*;
    import javax.swing.border.EmptyBorder;
    
    public class GameWindow extends JFrame {
    
       private JPanel contentPane;
       private Grid world;
    
       public static void main(String[] args) {
          EventQueue.invokeLater(new Runnable() {
             public void run() {
                try {
                   play();
                } catch (Exception e) {
                   e.printStackTrace();
                }
             }
    
          });
       }
    
       private static void play() {
          GameWindow frame = new GameWindow();
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
    
       }
    
       /**
        * Create the frame.
        */
       public GameWindow() {
          world = new Grid(25, 43);
          world.setFocusable(true);
          world.requestFocusInWindow();
          
          int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
          InputMap inputMap = world.getInputMap(condition);
          ActionMap actionMap = world.getActionMap();
          
          final KeyStroke[] keyStrokes = {
                KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0),
                KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0),
                KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0),
                KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0)
          };
          for (final KeyStroke keyStroke : keyStrokes) {
             inputMap.put(keyStroke, keyStroke.toString());
             actionMap.put(keyStroke.toString(), new AbstractAction() {
                
                @Override
                public void actionPerformed(ActionEvent e) {
                   world.handleKeyPress(keyStroke.getKeyCode());
                }
             });
          }
          AbstractAction keyAction = new AbstractAction() {
             @Override
             public void actionPerformed(ActionEvent e) {
                int keyPressed = 0;
                world.handleKeyPress(keyPressed);
             }
          };
          
          
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          //setBounds(700, 700, 750, 700);
          setPreferredSize(new Dimension(750, 700));
          contentPane = new JPanel();
          contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
          setContentPane(contentPane);
          GridBagLayout gbl_contentPane = new GridBagLayout();
          gbl_contentPane.columnWidths = new int[] { 243, 0, 0 };
          gbl_contentPane.rowHeights = new int[] { 433, 0, 0 };
          gbl_contentPane.columnWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
          gbl_contentPane.rowWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
          contentPane.setLayout(gbl_contentPane);
          JPanel gameAreaView = world;
          GridBagConstraints gbc_gameAreaView = new GridBagConstraints();
          gbc_gameAreaView.gridwidth = 2;
          gbc_gameAreaView.insets = new Insets(0, 0, 5, 0);
          gbc_gameAreaView.anchor = GridBagConstraints.NORTH;
          gbc_gameAreaView.fill = GridBagConstraints.BOTH;
          gbc_gameAreaView.gridx = 0;
          gbc_gameAreaView.gridy = 0;
          contentPane.add(gameAreaView, gbc_gameAreaView);
          gameAreaView.setLayout(new GridLayout(1, 1, 0, 0));
          JPanel UserMenu = new JPanel();
          GridBagConstraints gbc_UserMenu = new GridBagConstraints();
          gbc_UserMenu.fill = GridBagConstraints.BOTH;
          gbc_UserMenu.gridx = 1;
          gbc_UserMenu.gridy = 1;
          contentPane.add(UserMenu, gbc_UserMenu);
          UserMenu.setLayout(new GridLayout(0, 1, 0, 0));
    
          JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
          UserMenu.add(tabbedPane);
    
          JPanel abilities = new JPanel();
          tabbedPane.addTab("Abilities", null, abilities, null);
    
          JPanel quests = new JPanel();
          tabbedPane.addTab("Quests", null, quests, null);
    
          JPanel inventory = new JPanel();
          tabbedPane.addTab("Inventory", null, inventory, null);
    
          JPanel Stats = new JPanel();
          tabbedPane.addTab("Stats", null, Stats, null);
       }
    
    }
    
    class Grid extends JPanel {
       private Cell[][] cells;
       private int lastKeyPressed;
       private JPanel gameFrame = new JPanel();
    
       public Grid(int numRows, int numCols) {
          init(numRows, numCols);
       }
    
       private void init(int numRows, int numCols) {
          lastKeyPressed = -1;
          cells = new Cell[numRows][numCols];
          for (int row = 0; row < numRows; row++) {
             for (int col = 0; col < numCols; col++)
                cells[row][col] = new Cell();
          }
          // gameFrame.addKeyListener(this);
          int cellSize = Math.max(Math.min(500 / numRows, 500 / numCols), 1);
          setPreferredSize(new Dimension(cellSize * numCols, cellSize * numRows));
          gameFrame.add(this);
       }
    
       public void keyPressed(KeyEvent e) {
          lastKeyPressed = e.getKeyCode();
          handleKeyPress(lastKeyPressed);
       }
    
       public void handleKeyPress(int keyPressed) {
          int key = keyPressed;
          if (key == 38)// up
          {
             System.out.println("up");
          } else if (key == 40)// down
          {
             System.out.println("Down");
          } else if (key == 37)// left
          {
             System.out.println("left");
          } else if (key == 39)// right
          {
             System.out.println("right");
          }
       }
    }
    
    class Cell {
       public Cell() {
       }
    }

  5. #5
    StaticFlow is offline Member
    Join Date
    May 2012
    Posts
    17
    Rep Power
    0

    Default Re: KeyPress event controlling wrong component in JFrame

    Thanks that fixed it!

  6. #6
    StaticFlow is offline Member
    Join Date
    May 2012
    Posts
    17
    Rep Power
    0

    Default Re: KeyPress event controlling wrong component in JFrame

    hey quick question how would i do that same thing you did for keyPress events except for mouseClick events

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

    Default Re: KeyPress event controlling wrong component in JFrame

    Quote Originally Posted by StaticFlow View Post
    hey quick question how would i do that same thing you did for keyPress events except for mouseClick events
    Use a MouseListener. The Java Swing tutorials will show you how.

  8. #8
    StaticFlow is offline Member
    Join Date
    May 2012
    Posts
    17
    Rep Power
    0

    Default Re: KeyPress event controlling wrong component in JFrame

    well i have a mouseListener in the Grid class but the JPanel with the grid in it doesnt respond to the clicks does the listener need to be above it in the GameWindow class?

  9. #9
    StaticFlow is offline Member
    Join Date
    May 2012
    Posts
    17
    Rep Power
    0

    Default Re: KeyPress event controlling wrong component in JFrame

    never mind i got it.

Similar Threads

  1. Replies: 18
    Last Post: 10-04-2011, 10:56 AM
  2. a Component on top of all jframe components
    By shomid in forum AWT / Swing
    Replies: 2
    Last Post: 09-10-2011, 04:46 PM
  3. Replies: 1
    Last Post: 04-10-2011, 03:06 PM
  4. Nullifying Keypress or KeyTyped Event
    By tomtraxler in forum New To Java
    Replies: 3
    Last Post: 01-09-2011, 02:19 PM
  5. Identifying sender on keypress event
    By tomtraxler in forum NetBeans
    Replies: 1
    Last Post: 01-08-2011, 05:49 PM

Tags for this Thread

Posting Permissions

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