Search code examples
javaswinguser-interfacekey-bindingskeylistener

capture key press within frame


This seems like a simple behavior, but I'm having difficulty making it happen. I'm working on software which graphs data. I want to redraw the graph when the user hits enter. Well more accurately I want to draw the graph when the user hits enter and doesn't have a text field selected; but for now I'll be satisfied with drawing whenever the user hits enter.

I tried installing a basic KeyListener to the frame first, but that doesn't work since the JFrame children, not the frame, receive the event.

I then tried to use the KeyEventDispatcher, but it's proving too global a concept. I can have two graphs on screen at once, and an old graph can be closed or replaced with a new graph. With the KeyEventDispatcher I have no easy way of knowing which plot I want to activate out of the multiple plots open at a time and the plots currently open now may not be the plots that were opened when I instantiated the key dispatcher. I know this solution could still work, but it requires my storing extra data as to what plot is currently active that doesn't fit well into the program architecture.

It seems as if there should be an easier method to capture any KeyEvents dispatched to a JFrame/JPanel or any of the JFrame's children; but ignore events dispatched to other frames. Preferable a method that can be added to the frame and thus is automatically disposed when the frame is disposed. Can anyone suggest a simpler method then what I've tried?


Solution

  • Don't use a KeyListener.

    Add a Key Binding to the graph panel.