I'm trying to make a program that will toggle a boolean value and paint a red rectangle on the right side of a swing panel when you press the 'a' key. Unfortunately, I'm not having much luck, because when I hit 'a' nothing happens. My mistake is probably something obvious that I'll know how to fix once someone points it out for me, but for the life of me, I can't find it. If someone could look over my code and figure out what's wrong, I'd very much appreciate it. I've attached my source code below.

Recommended Answers

All 8 Replies

First thing is try to debug the code by adding println()s to see where the code is executing.
The code does not compile:

ClickyLatinHelp.java:78: cannot find symbol
symbol  : class Lists
location: class ClickyLatinHelp.DrawingArea
    	Lists listhi = new Lists();
    	^
ClickyLatinHelp.java:78: cannot find symbol
symbol  : class Lists
location: class ClickyLatinHelp.DrawingArea
    	Lists listhi = new Lists();
    	                   ^
ClickyLatinHelp.java:68: warning: [serial] serializable class ClickyLatinHelp.DrawingArea has no definition of serialVersionUID

	public class DrawingArea extends JPanel {
	       ^
ClickyLatinHelp.java:5: warning: [serial] serializable class ClickyLatinHelp has no definition of serialVersionUID
public class ClickyLatinHelp extends JFrame implements ActionListener, KeyListener {
       ^
2 errors
2 warnings

4 error(s)

Could it be that it doesn't compile becasue you don't have the .class file for the Lists class I made?

Have you tried debugging your code using println()s?

the obvious questions:
Do you have key listeners?
are they connected to any components?
Does the component have focus?

Yeah, it's showing that for some reason, my program isn't picking up on key events, even though I implemented the key Listener interface and overrode it's methods.

Re-read NormR1's second question and check your code again.

are they connected to any components?

What do you mean by: "are they connected to any components?" The key listener is implemented in the driver class and the extended JPanel is focusable.

You must add the KeyListener to a component with the addKeyListener() method. It's similar to what you did with the ActionListener for the buttons.

Implementing the interface just defines what the listener does. Then you attach it to the component you want to listen to.

OH! Duh! Sorry, the book I'm learning java from didn't mention a thing about having to use an addKeyListener() method. Now everything makes sense. Thanks so much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.