tags:

views:

103

answers:

3

Hi, I'm battling an error I don't quite understand. I have a class in Java, let's call it DownloadTable derived from a JDTable. Each of these classes implement KeyListener.

I'd like the base class JDTable to handle some keystrokes, so I put this.AddListener(this) in its constructor and create a key handler

public void keyPressed(KeyEvent e) {...}

then I'd like the derived class DownloadTable to do some special keyboard processing of its own, so I repeat the process and add keyboard handler there too. I also added a call to super.processKeyEvent() from the derived class' key handler to wire together the derived handler and the base handler.

The problem is that it doesn't work as expected and I'm getting a stack overflow exception whenever super.ProcessKeyEvent is called. When run in debugger, the parent's event handler isn't even called. Am I missing something obvious? Isn't super.processKeyEvent() going to somehow invoke superclass' keyPressed() handler? Thanks.

attached stack:

Exception in thread "AWT-EventQueue-1" java.lang.StackOverflowError at jd.gui.swing.jdgui.views.downloadview.DownloadTable.keyPressed(DownloadTable.java:253) at java.awt.Component.processKeyEvent(Unknown Source) at javax.swing.JComponent.processKeyEvent(Unknown Source) at jd.gui.swing.jdgui.views.downloadview.DownloadTable.keyPressed(DownloadTable.java:253) at java.awt.Component.processKeyEvent(Unknown Source) at javax.swing.JComponent.processKeyEvent(Unknown Source) at jd.gui.swing.jdgui.views.downloadview.DownloadTable.keyPressed(DownloadTable.java:253) at java.awt.Component.processKeyEvent(Unknown Source)

+1  A: 

When processKeyEvent() calls the registered listeners to propagate key events, a listener should not call back to processKeyEvent() or the result is an infinite recursion as you have seen.

What is the reason you added the call? Is something ot working when you remove it?

rsp
+1  A: 

I'd like the base class JDTable to handle some keystrokes

You should NOT be overriding the processKeyEvent(). You should be using Key Bindings. The provided link shows you the existing binds for each Swing component and provides a link to the Swing tutorial on "Using Key Bindings".

camickr
A: 

Thanks for the replies, all of them are correct.

Apparently I've figured out the problem. I've mixed up awt's processKeyEvent() and KeyListener.

The proper solution to this was to add

this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) { ...

to the base method. Now events in both base and derived methods are being handled.

Still, the weird thing is that KeyAdapter works for me and KeyListener does not. What's not working is when I make the base class implement KeyListener and add method public void keyPressed(KeyEvent e) { ... } - it never gets called. As I said above, when I use KeyAdapter inline, it gets executed.

Axarydax