Reputation: 1
I've been trying to make this text game where the user has a UI that they simply type commands into a JTextField and the game plays out in the JTextArea. Classic RPG sort of style. I've been having issues using a KeyListener to try and see when the user presses the "enter" key which puts what they said into the JTextArea and then clears the JTextField. It had worked before no problem, the JTextField would clear and everything was perfect. Then after I tried to add a JTextArea.append(text); to the mix, everything broke. Even after taking it away the function would now come up with the same error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at UITest.keyReleased(UITest.java:17)
As I said before I already tried moving it back into its original state but this didn't work. I also looked up the issue and some said I needed to add a KeyEvent.consume(); and so I tried that as well but it did nothing. The same error continues to occur.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class UITest implements KeyListener{
private JFrame main;
private JTextArea mainText;
private JTextArea input;
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode()== KeyEvent.VK_ENTER) {
e.consume();
System.out.println("pressed");
String text = input.getText();
input.setText("");
mainText.append(text);
}
}
public void keyTyped(KeyEvent e) {}
public void actionPerformed(ActionEvent e) {}
public UITest(){
main=new JFrame("Text Game");
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setSize(1366,768);
mainText=new JTextArea("Testing");
mainText.setBounds(10,100,1366,728);
mainText.setEditable(false);
JTextField input=new JTextField("");
input.setBounds(10,700,1366,20);
input.addKeyListener(this);
main.add(input);
main.add(mainText);
main.pack();
main.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new UITest();
}
});
}
}
I'd expected this to simply get the text from JTextField and set it to a temporary String, text, then to erase the JTextField and add text to the JTextArea. Of course, this didn't happen and all I got in return was a NullPointerException error. Any help would be greatly appreciated. This code has been a thorn in my side for ages.
Upvotes: 0
Views: 64
Reputation: 83537
input.setText("");
This is the line which causes the error because you have not initialized input
to a value yet.
Note that you have two variables with the same name. In your class, you have a field declared as:
private JTextArea input;
and in the constructor you have:
JTextField input=new JTextField("");
Since this is a local variable in the constructor, it is not available to other methods. Change this line to
input=new JTextField("");
Upvotes: 2