Showing posts with label events. Show all posts
Showing posts with label events. Show all posts

Eating the Keys

I am learning about the finer points of GUI development with Java this week. It turns out there are some GUI basics in Java that I don't know about. So I am studying them first. One topic of interest is catching events. To practive, I started coding up an event viewer. It is supposed to get and print out events that fire based on a bunch of different GUI components.

For the most part I can knock out the even viewer code. I am setting up listeners that log events to the screen. Then I try to do a KeyListener. But my event handlers are not getting called. What the heck? Initially my text area control was displaying the keys. Okay. I disabled it. Still no keyboard events.

I am a good debugger. I traced the issue down to the presence of a JButton on my GUI. If I remove the JButton, the keyboard events fire and I get the calls. What could be going on here? Is the JButton receiving and eating up the keyboard events? It looks like I am going to have to consult an expert here.

Button Action Command

Normally you have your applet listen for actions from your controls like the buttons in your applet. The event handler gets the action command. That command is normally the text on the button itself.

Recently I have been creating buttons that have no text. They just display an image that I loaded as the icon of the button. How does the applet know which control generated the event?

It turns out that you can call setActionCommand and pass it a String. This String is when the applet will get when it tries to get the command. It puts you back in control for the event processing.

Here is a tip I discovered the hard way. Make sure you addActionListener(this) on the button you want to handle events for. Otherwise the applet will never get a notification that your button was clicked. This might be obvious. But it is painful to debug when you forget to make the call.