【发布时间】:2013-05-01 16:37:28
【问题描述】:
这是我几乎完成的选择你自己的冒险游戏。 Actionlistener 坏了。它适用于“互联网”部分,但 Actionlistener 的其余部分不会使按钮更改文本。
Actionlistener 的其余部分与第一部分非常相似。
请帮忙。
编辑:去掉不相关的部分
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
public class TheGame extends JPanel implements ActionListener{
/**
* @param args
*/
String gameText = "You wake up in the morning feeling like a sir. As is tradition, you need electronics of any kind to keep your mind running (going outside is out of the question. Nothing exciting in the real world). There are many options available to you, but the internet and games are the ones that appeal the most. Do you want to surf the web or use an app?";
private final JTextArea adventureArea;
private static final long serialVersionUID = 1L;
JButton option1;
JButton option2;
public TheGame(){
option1 = new JButton("Click here for teh interwebs");
option1.addActionListener(this);
option1.setPreferredSize(new Dimension(300, 50));
option1.setVisible(true);
option2 = new JButton("Click here for teh entertainments");
option2.addActionListener(this);
option2.setPreferredSize(new Dimension(300, 50));
option2.setVisible(true);
this.adventureArea = new JTextArea(24, 80);
adventureArea.setFont(new Font("Serif", Font.PLAIN, 16));
adventureArea.setLineWrap(true);
adventureArea.setWrapStyleWord(true);
adventureArea.setEditable(true);
adventureArea.setText(gameText);
}
动作监听器:
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==option1){//internets
String gameText="";
adventureArea.setText(gameText);
option1.setText("Dark!");
option2.setText("Light!");
if(e.getSource()==option1){//Dark
//String gameText="";
//adventureArea.setText(gameText);
}if (e.getSource()==option2){//Light
//gameText="");
option1.setText("Ponies!");
option2.setText("Videos!");
if(e.getSource()==option1){//Ponies
gameText="";
adventureArea.setText(gameText);
option1.setText("Read!");
option2.setText("Socialize!");
if(e.getSource()==option1){//Read
gameText="";
adventureArea.setText(gameText);
option1.setText("Leave!");
option2.setText("Leave!");
if(e.getSource()==option1){//leave
System.exit(0);
}else if (e.getSource()==option2){//leave
System.exit(0);
};
}else if (e.getSource()==option2){//socialize
gameText="";
adventureArea.setText(gameText);
option1.setText("Leave!");
option2.setText("Leave!");
if(e.getSource()==option1){//leave
System.exit(0);
}else if (e.getSource()==option2){//leave
System.exit(0);
};
};
【问题讨论】:
-
我的天啊,我喜欢阅读对问题的糟糕描述,并在大量的 sn-p 代码中滚动查看有问题的部分。谢谢。
-
那是一个巨大的sn-p代码没有行号:-(
-
像这个例子这样好的演示文稿,真的很有帮助。哈哈
-
有时,我喜欢向后靠,想象这些“开发人员”与他们的同学/同事的对话。
-
呃。对十亿个 if-else-if 的每个按钮的操作侦听器使用匿名或内部类。这将为您和其他阅读您的代码的人简化它。
标签: java swing jbutton actionlistener jtextarea