Я пытаюсь сделать простую текстовую RPG, но застрял в самом начале.
Я узнал Java уже около месяца и каким-то образом смог создать простую текстовую приключенческую игру (используя Scanner, println, if-statement и т.д.), Который работает на CMD.
Поэтому я решил сделать немного более продвинутый (надеюсь, похожий на Wizardry материал), который можно сыграть в окне.
До сих пор я узнал, как сделать окно с рамкой и поместить некоторые панели, текстовые области и т.д. Но теперь я ударяю о стену.
То, что я пытаюсь сделать (но не могу сделать), это:
Вот мой код:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main extends JFrame implements ActionListener
{
JFrame window;
JPanel p1;
JPanel p2;
JPanel p3;
JPanel p4;
JPanel p5;
JButton graphic;
JTextArea statusT;
JTextArea storyT;
JTextField input;
JButton commandB1;
JButton commandB2;
JButton commandB3;
JButton commandB4;
JButton commandB5;
public static void main(String[]args)
{
Main game = new Main();
game.opening();
}
public void opening()
{
JFrame window = new JFrame();
window.setBounds(200,200,1024,768);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBackground(Color.black);
window.setLayout(null); //Disabling the default layout.
Font basicfont = new Font("MS Gothic", Font.PLAIN, 20);
// Panel Setup
JPanel p1 = new JPanel(); //This is where graphics are displayed.
p1.setBounds(10, 10, 650, 350); //Panel layout(x,y,x,y)
p1.setBackground(Color.black);
JPanel p2 = new JPanel(); //This is where status is displayed.
p2.setBounds(670, 10, 325, 350);
p2.setBackground(Color.black);
JPanel p3 = new JPanel(); //This is where story text is displayed.
p3.setBounds(10, 370, 650, 350);
p3.setBackground(Color.black);
JPanel p4 = new JPanel(); //This is where command menu is displayed.
p4.setBounds(670, 370, 325, 300);
p4.setBackground(Color.black);
p4.setLayout(new GridLayout(5,1)); //Setting the layout of Panel 4
JPanel p5 = new JPanel(); //This is the text-entry box.
p5.setBounds(670, 680, 325, 50);
// TextArea Setup
JTextArea statusT = new JTextArea();
JTextArea storyT = new JTextArea();
JTextField input = new JTextField(32);
JButton commandB1 = new JButton("1:Stay");
JButton commandB2 = new JButton("2:Attack the man");
JButton commandB3 = new JButton("3:Drink");
JButton commandB4 = new JButton("4:Leave");
JButton commandB5 = new JButton("5:(Debug)Clear the text");
//Graphic setup
//graphic = new JButton(new ImageIcon("dungeonSample.jpg"));
//graphic.setBackground(Color.black);
//Status text setup
statusT.setFont(basicfont);
statusT.setBackground(Color.black);
statusT.setForeground(Color.white);
statusT.setText("\nLV 6\nHP 100\nMP 28\nG 120\nEXP 36"); //Ths is just a sample status
//Story text setup
storyT.setFont(basicfont);
storyT.setBackground(Color.black);
storyT.setForeground(Color.white);
storyT.setText("<The innkeeper>\nHello this is an adventurer inn. 8 golds for a night. \nWhat do you want to do?");
//Input box setup
input.setFont(basicfont);
input.setBackground(Color.black);
input.setForeground(Color.white);
//input.setText("Input a number here>");
input.addActionListener(this);
// Add Text>>Panel>>Window
//p1.add(graphic);
p2.add(statusT);
p3.add(storyT);
p4.add(commandB1);
p4.add(commandB2);
p4.add(commandB3);
p4.add(commandB4);
p4.add(commandB5);
p5.add(input);
window.add(p1);
window.add(p2);
window.add(p3);
window.add(p4);
window.add(p5);
window.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String choice = input.getText();
if(choice.equals("1")){
storyT.setText("All right, sleep well.");
}
if(choice.equals("2"))
{
storyT.setText("What, you think you can rob me?!\n\nThe inkeeper attacked!\n6870 points of damage!\nYou are dead.");
}
if(choice.equals("3"))
{
storyT.setText("Sorry, we can't serve booze anymore because of the restriction by the lord");
}
if(choice.equals("4"))
{
storyT.setText("See ya.");
}
if(choice.equals("5"))
{
storyT.setText("");
}
}
}
В этой примерной ситуации я надеялся, что если вы введете "1" в поле ввода (текстовое поле на панели p5), диалог по умолчанию хозяина гостиницы ("Привет, это путешественник-искатель приключений...") будет заменен на строка "Хорошо, хорошо спать". Но даже если я вхожу "1" (или любой другой номер), ничего не меняется, и на консоли отображается сообщение об ошибке.
Я также попытался очистить текст по умолчанию, введя "5" в текстовое поле, но это также не работает.
Я знаю, что я что-то сделал не так, но я не знаю, где это. Я попытался найти решение в Интернете, но пока не нашел никакой эффективной информации.
Я буду очень благодарен, если кто-нибудь скажет мне, что я должен делать.
изменить это
JTextArea statusT = new JTextArea();
JTextArea storyT = new JTextArea();
JTextField input = new JTextField(32);
к этому
statusT = new JTextArea();
storyT = new JTextArea();
input = new JTextField(32);
вы не инициализируете текстовые поля, которые вы создали как экземпляр. Вы создаете новый файл textareas.so, поэтому textareas имеет значение null.that, почему вы получаете исключение нулевого указателя
JTextArea statusT;
JTextArea storyT;
JTextField input;
эти три еще не начаты. Не создавайте еще один statusT,storyT,input
как локальный.