简体   繁体   English

java —如何使每次单击按钮时都出现新的文本块

[英]java — how to make new text block appear every time a button is clicked

I'm new at Java and trying to make a simple interactive fiction game with a GUI using swing. 我是Java的新手,正在尝试使用swing使用GUI创建一个简单的交互式小说游戏。 Right now I'm trying to break a large block of text into sections so it will fit onto the screen easily. 现在,我正在尝试将一大段文本分成几部分,以便将其轻松地放在屏幕上。 I want one block of text to show in a Jtextarea with a "continue" Jbutton on the bottom of the screen, where every time a user clicks the Jbutton the current text will disappear and be replaced with new text. 我希望一个文本块显示在屏幕底部的Jtextarea中,并带有“ continue” Jbutton,每次用户单击Jbutton时,当前文本将消失,并被新文本替换。 Here's the relevant code: 以下是相关代码:

    public class forwardScreenHandler implements ActionListener{
    public void actionPerformed(ActionEvent event){
        mainTextArea.setText("Nice change!");
        mainTextArea.setText("do it again!");
        mainTextArea.setText("Please be third!");

            }
        }

public void chooseYes(){
    yesnoButtonPanel.setVisible(false);
    continueButtonPanel.setVisible(true);
    continueButtonPanel.setBackground(Color.red);
    continueButton.removeActionListener(contHandler);
    continueButton.addActionListener(userCont);
    position = "yes";
    mainTextArea.setText("Blah Blah Blah");

}

Clearly the code will result in "blah blah blah" being initially shown, then when I click the continue button the final setText "Please be third!". 显然,该代码将导致最初显示“等等等等”,然后当我单击“继续”按钮时,最后的setText为“请成为第三名!”。 I understand it's because I haven't written any code telling Java to setText every time the continue button is clicked, but I can't figure out how to do this. 我知道这是因为我没有编写任何代码来告诉Java每次单击继续按钮时都要setText,但是我不知道该怎么做。 Like I said I'm a beginner, so any explanation would be helpful so I can understand what to do. 就像我说的我是初学者一样,所以任何解释都将对您有所帮助,这样我就可以知道该怎么做。

You need to use a variable and if statements to do this. 您需要使用变量和if语句来执行此操作。

Declare a variable at the class level to store how many times the button has been pressed: 在类级别声明一个变量,以存储按钮被按下的次数:

private int buttonPressCount = 0;

In the action listener for the continue button, first increment this variable, then set text based on the value of it. 在“继续”按钮的动作侦听器中,首先递增此变量,然后根据其值设置文本。

buttonPressCount++;
switch (buttonPressCount) {
    case 1:
        mainTextArea.setText("Nice change!");
        break;
    case 2:
        mainTextArea.setText("do it again!");
        break;
     case 3:
        mainTextArea.setText("Please be third!");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM