Accelerator key on ChartPanel in Swing?

A discussion forum for JFreeChart (a 2D chart library for the Java platform).
Locked
JGoodwin
Posts: 27
Joined: Thu Sep 06, 2007 3:19 am
Location: Boston USA

Accelerator key on ChartPanel in Swing?

Post by JGoodwin » Sun Sep 13, 2009 8:39 pm

Hello all,

I have a subclass of ChartPanel and I want it to respond when the user types
a backspace by reverting the chart to a previous state. How do I go about
making the chart respond to backspace?

My first idea was to override createPopupMenu from ChartPanel and add a
new item "Back" to that menu, and then put an accelerator key on that item.
I got the item to work ok: it appears in the menu and if you choose it, it
runs my action.

Then I wrote:

Code: Select all

char backspace = KeyEvent.VK_BACK_SPACE;
item.setAccelerator(KeyStroke.getKeyStroke(backspace));
But I cannot get it to respond to what I type, not for backspace or
any other character either.

Do I have to turn on the capability to respond to accelerator keys
somewhere?

Is there a better way to do this? I don't care whether the
command is on the popup menu or not; I just want it to respond to
the keystroke. I could perhaps live with another key if it turns out
that Backspace [ascii 8] is a problem in some way.

Thanks
Jim Goodwin

skunk
Posts: 1087
Joined: Thu Jun 02, 2005 10:14 pm
Location: Brisbane, Australia

Re: Accelerator key on ChartPanel in Swing?

Post by skunk » Sun Sep 13, 2009 9:33 pm

Did you try something like this yet?

Code: Select all

chartPanel.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "foo");
chartPanel.getActionMap().put("foo", new AbstractAction() {
    public void actionPerformed(ActionEvent actionEvent) {
        // whatever
    }
});
Note that by default Swing JPanels are not focusable, so you MAY need this in a mouse handler

Code: Select all

chartPanel.requestFocus();

JGoodwin
Posts: 27
Joined: Thu Sep 06, 2007 3:19 am
Location: Boston USA

Re: Accelerator key on ChartPanel in Swing?

Post by JGoodwin » Sun Sep 13, 2009 9:58 pm

MUCH better.

Many thanks

Jim

david.gilbert
JFreeChart Project Leader
Posts: 11734
Joined: Fri Mar 14, 2003 10:29 am
antibot: No, of course not.
Contact:

Re: Accelerator key on ChartPanel in Swing?

Post by david.gilbert » Mon Sep 14, 2009 9:39 pm

Interesting, thanks Skunk for the answer!
David Gilbert
JFreeChart Project Leader

:idea: Read my blog
:idea: Support JFree via the Github sponsorship program

Locked