写一个基于文本的游戏,我很困惑如何检查按钮按下输入然后更新

时间:2013-06-08 12:46:14

标签: java applet

到目前为止,我有一个主类,消息类和一个答案类。消息和答案存储在单独的数组中,因此我可以在需要时将它们拉出来。但是,我不确定如何继续。我需要检查用户在点击“继续”按钮时输入的内容以及该消息的相应答案数组。 (一条消息将拥有自己的检查答案数组)。如果有更好的方法,即每个消息的案例陈述,请告诉我。这是代码:

主:

package com.game.main;

import java.applet.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main extends Applet {

private TextField commandInput;
private TextArea messageDisplay;
private Button button;
public Message messages;
private String currentLevel;

private boolean running = false;
private Thread thread;
private ActionListener action;

public synchronized void start() {
    running = true;
    thread = new Thread();
    thread.start();
}

public synchronized void stop() {
    running = false;
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

// Initialisation method
public void init() {
    super.init();

    messages = new Message();
    // Define colours
    setBackground(Color.white);
    setForeground(Color.black);

    Panel appletPanel = new Panel();

    // Use a border layout
    BorderLayout b = new BorderLayout();
    appletPanel.setLayout(b);
    add(appletPanel);

    this.setSize(800, 400);

    // Define UI items
    commandInput = new TextField(20);
    messageDisplay = new TextArea(null, 20, 60, TextArea.SCROLLBARS_NONE); // 20 rows x 60 chars
    button = new Button("Proceed");
    Panel inputPanel = new Panel();

    // Add components to our layout / panels
    inputPanel.add(commandInput);
    inputPanel.add(button);
    appletPanel.add(messageDisplay, "North");
    appletPanel.add(inputPanel, "South");

    currentLevel = messages.messageArray[0];
    messageDisplay.append(messages.messageArray[0]);

    run();
}

// game loop
public void run() {
    requestFocus();
    // read as while "running == true"
    while (running) {

    }
}

}

消息:

package com.game.main;

public class Message {

public String[] messageArray;

public Message() {
    messageArray = new String[50];
    messageArray[0] = "Welcome.";
}
}

数目:

package com.game.main;

public class Answers {

public String[] introAnswers;

public Answers() {
    introAnswers = new String[2];
    introAnswers[0] = "Go";
    introAnswers[1] = "go";
}

}

1 个答案:

答案 0 :(得分:3)

您需要使用EventListener,以便程序可以检测按钮何时被按下并检查textArea中的文本。看看这个tutorial

这是一个简单的通用示例:

button.addActionListener (new ActionListener () {
    public void actionPerformed(ActionEvent e) {
        message = textArea.getText();
        //Do stuff
    }
});