0

我正在 Java Applet 中创建一个文本游戏,因此我可以在我的网站上显示它并让人们在那里玩它,但是我无法在我的 TextArea 中显示任何文本。

这是我的主要课程:

package com.game.main;

import java.applet.*;
import java.awt.*;

public class Main extends Applet {

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

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

        // 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(20, 60); // 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("North", messageDisplay);
        appletPanel.add("South", inputPanel);

        messageDisplay.append(messages.getIntro());
    }
}

这是我的 Messages 类(它包含所有消息,当用户点击按钮时,它将使用 getWhateverMessage 方法附加下一条消息:

package com.game.main;

public class Message {

    public String currentMessage;

    public String getCurrentMessage() {
        return currentMessage;
    }

    public void setCurrentMessage(String message) {
        currentMessage = message;
    }

    public String getIntro() {
        return "Welcome, This is a text adventure game created by me, Adam Short, as a little project to " +
               "exercise storytelling as well bring a retro style game to you, the player. To play this " +
               "game all you need is a keyboard to type your answers into the input box below. Keep your " +
               "answers relevant or you won't progress through the game at all. Type your answer into the " +
               "input box and hit the Proceed button or enter on your keyboard. Different answers will lead " +
               "to different scenearios and sequences of events. Be careful. Ready to go? Type go in the box " +
               "and hit Proceed!";
    }
}
4

2 回答 2

5
public Message messages;
...
messageDisplay.append(messages.getIntro());

您定义了为 null 的消息变量,但您从未创建 Message 类的实例。

您需要在代码中的某处:

messages = new Message();

在定义变量时执行此操作,或者在使用变量之前在构造函数中的某个位置执行此操作。

appletPanel.add("North", messageDisplay);
appletPanel.add("South", inputPanel);

另外,上面的代码是错误的。阅读 add() 方法的 API。建议您使用:

appletPanel.add(messageDisplay, BorderLayout.NORTH);
appletPanel.add(inputPanel, BorderLayout.SOUTH);
于 2013-06-07T18:20:31.357 回答
2

camickr 是对的,你需要创建一个 Message 类的对象,并且变量 messages 需要持有对它的引用:

消息=新消息();

然后只有你可以访问它的实例变量和方法。

于 2013-06-07T18:29:34.683 回答