Results 1 to 11 of 11
  1. #1
    imorio is offline Senior Member
    Join Date
    Aug 2010
    Posts
    127
    Rep Power
    0

    Default keyListener not doing anything

    I wanted to add hotkeys to my program, so I made my class implement KeyListener, added the methodes and added a keylistener. But somehow, when I ran the program and clicked a key, the methode wasn't called, so clicking keys did nothing. Then I wrote a simple program, just to test if I could make any program respond to key-input. However this simple program also did nothing.

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class testClass extends JFrame implements KeyListener
    {
    	private boolean rectangle=false;
    	public toren()
    	{
    		setTitle("test");
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setSize(500, 500);
    		setLocation(0,0);
    		getContentPane().setBackground(Color.white);
    		((Component) getContentPane()).addKeyListener(this);
    		setVisible(true);
    	}
    	public void paint(Graphics g)
    	{
    		g.drawRect(50, 50, 50, 50);
    		if(rectangle)
    		{
    			g.drawRect(50, 50, 100, 100);
    		}
    	}
    	public void keyPressed(KeyEvent e) {
    	}
    	public void keyReleased(KeyEvent e) {
    	}
    	public void keyTyped(KeyEvent e) {
    		rectangle=true;
    		repaint();
    	}
    }
    Because the methode just isn't called, debugging didn't help. My question is, what am I doing wrong?

  2. #2
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    6

    Default

    Use KeyBindings instead of a keyListener, especially if you want a hotkey function for the complete frame.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  3. #3
    imorio is offline Senior Member
    Join Date
    Aug 2010
    Posts
    127
    Rep Power
    0

    Default

    ok, I went for keybinders (after looking up what they are), so now my code is:
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class toren extends JFrame implements KeyListener
    {
    	private boolean rectangle=false;
    	public toren()
    	{
    		setTitle("tower defence");
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setSize(500, 500);
    		setLocation(0,0);
    		getContentPane().setBackground(Color.white);
    		((Component) getContentPane()).getInputMap(WHEN_IN_FOCUSED_WINDOW).
    put(KeyStroke.getKeyStroke("b"),"doSomething");//<error
    		((Component) getContentPane()).getActionMap(WHEN_IN_FOCUSED_WINDOW).
    put("doSomething",rectangle());//<error
    		setVisible(true);
    	}
    	public void paint(Graphics g)
    	{
    		g.drawRect(50, 50, 50, 50);
    		if(rectangle)
    		{
    			g.drawRect(50, 50, 100, 100);
    		}
    	}
    	public void keyPressed(KeyEvent e) {
    	}
    	public void keyReleased(KeyEvent e) {
    	}
    	public void rectangle() {
    		rectangle=true;
    		repaint();
    	}
    }
    ".getInputMap(WHEN_IN_FOCUSED_WINDOW)" and ".getActionMap(WHEN_IN_FOCUSED_WINDOW)" still give an error. The statement seems wrong to me, but the sun tutorial doesn't give me any clue how the statement should read.

  4. #4
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    6

    Default

    Java Code:
    	public toren() {
    		setTitle("tower defence");
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setSize(500, 500);
    		setLocation(0, 0);
    		getContentPane().setBackground(Color.white);
    		((JComponent) getContentPane()).getInputMap (JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    				KeyStroke.getKeyStroke('b'), "doSomething");
    		((JComponent) getContentPane()).getActionMap()
    				.put("doSomething", doPaint);
    		setVisible(true);
    	}
    
    	Action doPaint = new AbstractAction() {
    	    public void actionPerformed(ActionEvent e) {
    	       rectangle();
    	    }
    	};
    And please read the custrom painting tutorial before you continue.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  5. #5
    imorio is offline Senior Member
    Join Date
    Aug 2010
    Posts
    127
    Rep Power
    0

    Default

    Quote Originally Posted by PhHein View Post
    Java Code:
    	public toren() {
    		setTitle("tower defence");
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setSize(500, 500);
    		setLocation(0, 0);
    		getContentPane().setBackground(Color.white);
    		((JComponent) getContentPane()).getInputMap (JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    				KeyStroke.getKeyStroke('b'), "doSomething");
    		((JComponent) getContentPane()).getActionMap()
    				.put("doSomething", doPaint);
    		setVisible(true);
    	}
    
    	Action doPaint = new AbstractAction() {
    	    public void actionPerformed(ActionEvent e) {
    	       rectangle();
    	    }
    	};
    And please read the custrom painting tutorial before you continue.
    Thank for the help. However the tutorial you recommended is rather bad. It uses the style "add code x, this will have result y", which is great when everything works. However after trying to add this code to my program, my program gave all kinds of errors and stopped working. Now with 20 lines of code in my program which I have no clue what they do, fixing this is almost impossible. My only option left is te remove all the code from the tutorial and return to the last state of my program that still worked.

  6. #6
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    6

    Default

    First of all you should not do any painting on the contentPane, but in a JPanel which is added to the contentPane. Then the tutorial code starts working automagically.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  7. #7
    imorio is offline Senior Member
    Join Date
    Aug 2010
    Posts
    127
    Rep Power
    0

    Default

    Quote Originally Posted by PhHein View Post
    First of all you should not do any painting on the contentPane, but in a JPanel which is added to the contentPane. Then the tutorial code starts working automagically.
    I did that, and now all I get is a list of error messages:

    Java Code:
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: adding a window to a container
    	at java.awt.Container.checkNotAWindow(Unknown Source)
    	at java.awt.Container.addImpl(Unknown Source)
    	at java.awt.Container.add(Unknown Source)
    	at javax.swing.JFrame.addImpl(Unknown Source)
    	at java.awt.Container.add(Unknown Source)
    	at tester.startEditor(tester.java:23)
    	at tester$1.run(tester.java:14)
    	at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)
    I painted the squares I wanted using pixels (as in "g.drawRect(x1, y1, x2, y2)" with x1-y2 being ints), could that cause problems?

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

    Default

    I think your problem is coming from somewhere else. It looks as if you're trying to add a JFrame (or other top level container) to a JPanel (or other Container).

    Perhaps you should show us the code that is causing the error.

  9. #9
    imorio is offline Senior Member
    Join Date
    Aug 2010
    Posts
    127
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    I think your problem is coming from somewhere else. It looks as if you're trying to add a JFrame (or other top level container) to a JPanel (or other Container).

    Perhaps you should show us the code that is causing the error.
    Thanks, I was extending JFrame when I should have been extending JPanel. Most of my program is working again with the huge improvement that when part of the window gets blocked, the content returns when it is unblocked. My only problem left is my JMenuBar.

    Adding it in the JPanel class editor (where I do almost everything) doesn't compile, using a get methode to get the menuBar from "editor" and then adding it in the tester class doesn't work either. If I add it after the JPanel, the whole screen turns into one big menuBar and when I add the menuBar first, it just doesn't show up. I tried moving the JPanel 50 pixels down, but that just revealed empty background.

    Java Code:
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    public class tester
    {
    	public static void main(String[] args)
    	{
    		SwingUtilities.invokeLater
    		(
    			new Runnable()
    			{
    				public void run()
    				{
    					startEditor();
    				}
    			}
    		);
        }
    	public static void startEditor()
    	{
    		JFrame f = new JFrame("towerDefence: editor");
    		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		editor e= new editor();//editor extends JPanel
    		f.add(e.getMenuBar());
    		f.add(e);
    		f.pack();
    		f.setVisible(true);
    	}
    	public static void nieuwSpel(ArrayList<Point> route, int veldGrootte)
    	{
    		new spel(route, veldGrootte);
    	}
    }

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

    Default

    Quote Originally Posted by imorio View Post
    Thanks, I was extending JFrame when I should have been extending JPanel.
    That makes more sense for the error that you're seeing.


    Most of my program is working again with the huge improvement that when part of the window gets blocked, the content returns when it is unblocked. My only problem left is my JMenuBar.

    Adding it in the JPanel class editor (where I do almost everything) doesn't compile,...
    I don't understand this since a JMenuBar extends from JComponent, you should be able to add it to a JPanel without any difficulty. Again, showing us code and the actual error message would help us greatly.


    using a get methode to get the menuBar from "editor" and then adding it in the tester class doesn't work either. If I add it after the JPanel, the whole screen turns into one big menuBar and when I add the menuBar first, it just doesn't show up. I tried moving the JPanel 50 pixels down, but that just revealed empty background.

    Java Code:
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    public class tester
    {
    	public static void main(String[] args)
    	{
    		SwingUtilities.invokeLater
    		(
    			new Runnable()
    			{
    				public void run()
    				{
    					startEditor();
    				}
    			}
    		);
        }
    	public static void startEditor()
    	{
    		JFrame f = new JFrame("towerDefence: editor");
    		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		editor e= new editor();//editor extends JPanel
    		f.add(e.getMenuBar());
    		f.add(e);
    		f.pack();
    		f.setVisible(true);
    	}
    	public static void nieuwSpel(ArrayList<Point> route, int veldGrootte)
    	{
    		new spel(route, veldGrootte);
    	}
    }
    Have a look at the JFrame API and you'll see a method that is used for specifically adding a JMenuBar to a JFrame, setJMenuBar. When you run into similar problems, always go to the API before coming here as it will likely give you the answer quicker and is a good skill to master.

  11. #11
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,562
    Rep Power
    23

    Default

    f.add(e.getMenuBar());
    What kind of component does the getMenuBar() method return?
    Is it appropriate to be adding that component to the content pane?
    See the JFrame class for other types of add/set methods

Similar Threads

  1. Help me in adding keylistener
    By kumarv75 in forum CLDC and MIDP
    Replies: 0
    Last Post: 06-22-2010, 07:10 AM
  2. KeyListener - Is this what I need?
    By dbashby in forum New To Java
    Replies: 26
    Last Post: 04-18-2009, 04:14 PM
  3. keyListener isn't working for me
    By lost_in_java in forum AWT / Swing
    Replies: 7
    Last Post: 12-05-2008, 04:24 AM
  4. KeyListener Example
    By Java Tip in forum SWT
    Replies: 0
    Last Post: 07-11-2008, 04:46 PM
  5. how to add a KeyListener
    By leonard in forum New To Java
    Replies: 1
    Last Post: 08-06-2007, 04:44 PM

Posting Permissions

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