[英]java — how to make new text block appear every time a button is clicked
我是Java的新手,正在尝试使用swing使用GUI创建一个简单的交互式小说游戏。 现在,我正在尝试将一大段文本分成几部分,以便将其轻松地放在屏幕上。 我希望一个文本块显示在屏幕底部的Jtextarea中,并带有“ continue” Jbutton,每次用户单击Jbutton时,当前文本将消失,并被新文本替换。 以下是相关代码:
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");
}
显然,该代码将导致最初显示“等等等等”,然后当我单击“继续”按钮时,最后的setText为“请成为第三名!”。 我知道这是因为我没有编写任何代码来告诉Java每次单击继续按钮时都要setText,但是我不知道该怎么做。 就像我说的我是初学者一样,所以任何解释都将对您有所帮助,这样我就可以知道该怎么做。
您需要使用变量和if语句来执行此操作。
在类级别声明一个变量,以存储按钮被按下的次数:
private int buttonPressCount = 0;
在“继续”按钮的动作侦听器中,首先递增此变量,然后根据其值设置文本。
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.