Right now, I am working on a text-based game that (ironically?) is in a GUI. I need to get user input (such as “Turn Left”, “Walk”) from a JTextField. I have had no success so far. The code is as follows.
package com.darkcartgames.textbased.epidemic;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Epidemic_TextBased {
private JFrame frame;
private JTextArea text;
private JPanel panel;
private JButton sendButton;
private JTextField jtext;
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
public static final String TITLE = "Epidemic TEXT | (C) 2014 DarkCart";
public static boolean running = false;
public static void main(String[] args) {
// It's so ironic that I'm gonna make a text-based game in a JFrame.
// LOL!
new Epidemic_TextBased();
}
public Epidemic_TextBased() {
frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
frame.setTitle(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
text = new JTextArea(10, 20);
text.setEditable(false);
frame.getContentPane().add(BorderLayout.CENTER, text);
text.append("(C) 2014 DarkCart Games \n \n");
text.append("STORY: \n");
text.append("Ah, there you are. I've been looking for you. \n");
text.append("Our village has been hit with a terrible epidemic. \n");
text.append("We need your help to find 4 bottles of medicine for the town. \n");
text.append("Will you do it? \n \n");
text.append("Type OK to help the town \n \n");
panel = new JPanel();
jtext = new JTextField(60);
sendButton = new JButton();
sendButton.setText("Send");
panel.add(jtext);
panel.add(sendButton);
frame.getContentPane().add(BorderLayout.SOUTH, panel);
sendButton.addActionListener(new sendButtonListener());
}
class sendButtonListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
String input = jtext.getText();
text.append(input + "\n \n");
if (input == "Ok") text.append("tester");
}
}
}
Could anyone help me with this?
Thanks,
DarkCart