我想使用圖形用戶界面進行總結性項目的Java基於文本的冒險遊戲,我遇到的問題是當我按下選項A ,它會起作用一次,之後不起作用。我還沒有添加任何選項B的東西,因爲如果我沒有辦法讓它在第一時間工作,它不會做任何好事。 import java.awt。*;基於文本的冒險遊戲使用GUI有能夠繼續按下按鈕的問題
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Project extends JFrame implements ActionListener {
private static final int WIDTH = 840;
private static final int HEIGHT = 480;
private JLabel gameText;
private JButton optionA, optionB, exitB;
private ExitButtonHandler ebHandler;
public project()
{
gameText = new JLabel("<HTML><br>You wake up in a forest, there is a path which
heads north. There also seems to be a old trail that leads deeper in the woods.</br>
</html>");
optionA = new JButton("Head North");
optionA.setActionCommand("optionA");
optionA.addActionListener(this);
optionB = new JButton("Go deeper into the forest.");
optionB.setActionCommand("optionB");
optionB.addActionListener(this);
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
setTitle("Adventuregame");
Container pane = getContentPane();
pane.setLayout(new GridLayout(4, 2));
pane.add(gameText);
pane.add(optionA);
pane.add(optionB);
pane.add(exitB);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("optionA"))
{
gameText.setText("<HTML><br>You find yourself on the pathway to a major capital
city, the walls of the kingdom head towards the sky and the gate is wide open, you can
hear the sounds of busy life from inside the castle gates. As you head in, a guard
confronts
you and asks why you are there.</br></HTML>");
optionA.setText("I'm lost and trying to find my way.");
optionB.setText("Ignore the guard");
optionA.setActionCommand("optionA2");
optionA.addActionListener(this);
if(e.getActionCommand().equals("optionA2"))
{
gameText.setText("<HTML><br>The guard checks you for weapons, finding nothing he
takes you to the tavern to find someone who may be able to help you out. In the Tavern
there are some drunkards singing in the corner and a band of mercenaries on your right.
At the bar there is a older man whom you seem to reconise</br></HTML>");
optionA.setText("Go towards the Mercenaries.");
optionB.setText("Go to the Older Man.");
optionA.setActionCommand("optionA3");
optionA.addActionListener(this);$
我試圖得到它使每一個我按下按鈕,將更新到下一 段時間,目前我一直無法找到如何做這種事。
btw你的構造函數必須像大寫的類名一樣,問題是你註冊了兩次sameActionListener到按鈕本身,你想做什麼我did not understand – nachokk
我想要做的很多事情是所以當你按下optionA時,它會執行第一個if語句,然後會出現A或B,如果再次按A,它會進入下一個,所以它會分支出來。我希望他們澄清一下?而對於班級名稱,我在這裏更改了它的名稱,因爲它涉及我的名字在實際版本上,因爲它是總結性的。還有一種方法可以將它從optionA更改爲新的,這樣我可以在我的代碼中工作嗎?或沒有? – user2501851
源代碼中的單個空白行是* always *就足夠了。 –