For this problem, my enter key for JTextField
is not initalizing the if-else
statement inside the chat();
I tried putting the userinput.addKeyListener(this);
inside public guitest();
as well but its not working.
How do I get it work so that I can initialize the if else statement to reply me an answer. The error given was:
Exception in thread "main" java.lang.NullPointerException
public class guitest extends JFrame implements KeyListener{
ArrayList questionarray = new ArrayList();
ArrayList answerarray = new ArrayList();
public JTextArea scriptarea = new JTextArea();
public JTextField userinput = new JTextField();
public String stringinput;
public ArrayList getquestionarray(){
return questionarray;
}
public ArrayList getanswerarray(){
return answerarray;
}
public guitest(){
//gui
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 600);
this.setVisible(true);
this.setResizable(false);
this.setLayout(null);
this.setTitle("Minion AI");
setLocationRelativeTo(null);
//jtextfield location and field
userinput.setLocation(7, 530);
userinput.setSize(580, 30);
//jtextarea location and size
scriptarea.setLocation(15, 5);
scriptarea.setSize(560, 510);
scriptarea.setEditable(false);
//adding methods to frame
this.add(userinput);
this.add(scriptarea);
chat();
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_ENTER){
stringinput = userinput.getText();
scriptarea.append("[You] " + stringinput + "\n");
userinput.setText("");
}
if(e.getKeyChar() == KeyEvent.VK_ESCAPE){
System.exit(0);
}
}
@Override
public void keyReleased(KeyEvent e) {
}
public void chat(){
Random random = new Random();
ArrayList greetingarray = greetings();
ArrayList quotesarray = quotes();
scriptarea.append("[AI Minion] "+greetingarray.get(random.nextInt(greetingarray.size()))+"\n");
userinput.addKeyListener(this);
if(greetingarray.contains(stringinput)){
for(int i=0; i<1; i++){
scriptarea.append("[AI Minion] "+greetingarray.get(random.nextInt(greetingarray.size()))+"\n");
}
}else if(questionarray.contains(stringinput)){
scriptarea.append("[AI Minion] "+answerarray.get(questionarray.indexOf(stringinput))+" \n");
}else if(stringinput.contains("who")){
scriptarea.append("[AI Minion] I am a creature created to assist you in your experience in talking to me. \n");
}else if(stringinput.contains("bye")||stringinput.contains("end")){
scriptarea.append("[AI Minion] Bye byee ♥‿♥ \n");
}else{
scriptarea.append("[AI Minion] Sorry, I dont understand your alien language. \n");
}
}
public static void main(String[] args){
new guitest();
}
}