gpt4 book ai didi

java - 尝试将字符串附加到 Java Applet 面板中的 TextArea 时出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 07:31:33 29 4
gpt4 key购买 nike

我正在 Java Applet 中创建一个文本游戏,以便可以在我的网站上显示它并让人们在那里玩它,但是我在让任何文本显示在我的 TextArea 中时遇到问题。

这是我的主要类(class):

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!";
}
}

最佳答案

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

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

您需要在代码中的某个位置:

messages = new Message();

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

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

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

appletPanel.add(messageDisplay, BorderLayout.NORTH);
appletPanel.add(inputPanel, BorderLayout.SOUTH);

关于java - 尝试将字符串附加到 Java Applet 面板中的 TextArea 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16990469/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com