The basic problem is one of context. input is declared as a local variable within the context of the constructor, so it can not be accessed from any other context
public void test()
{
//...
TextField input=new TextField("");
//...
}
To be honest, this is pretty basic Java 101, you should start by having a look at Understanding Class Members. This is a concept you should already understand before embarking on GUI development (IMHO)
Observations
- Avoid
KeyListener(generally), especially with text components - Use an
ActionListenerinstead - AWT is out-of-date, consider Swing or, better yet, JavaFX
- Avoid
nulllayouts, they will waste your time - As a general rule, you should not be extending directly from top level containers like
Frame. They lock you into a single use case, reduce re-usability and you're not really adding any new functionality to the class anyway
Videos
Your code won't compile since you didn't implement KeyListener (completely)
You didn't add the key listener to the panel in its constructor.
KeyEvents are only dispatched to components with focus. Your panel is not focusable so it will never receive events. You use the method
setFocusable(true).Don't override paint(). Instead you should be overriding
paintComponent(...).You shouldn't even be using a KeyListener. Instead when using Swing you should be using
Key Bindings.Don't use static variables for the properties of your class.
Your GUI is not created on the
Event Dispatch Thread (EDT).
i have read articles, i have watched videos, and done everything exactly like them,
Obviously not or it would work.
For a proper tutorial start with the Swing Tutorial. There are sections on:
- How to Write a KeyListener
- Custom Painting
- Key Bindings.
- Concurrency
Most importantly: change the name of your class. It's called main and that's a bad idea. Also it's much more advisable to override paintComponent() instead of paint.
You didn't add the keylistener to the JFrame. You should call this in your main after creating game:
frame.addKeyListener(game);
You also need to add the remaining KeyListener methods.
and that should do it.