java如何删除内部类ActionListener?
我正在做一个基于文本的游戏,但我有一个相当大的问题。这个问题是,当我将一个新的ActionListener分配给一个已经分配了ActionListener的按钮时,它会同时执行这两个操作。这是我的密码:
while(shouldLoop) {
if(Player.loc == 1) {
left.setText("Do nothing");
left.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
nar1.setText("You are still in a dungeon."); //Here's my first assignment
}
});
right.setText("Pick the lock");
right.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Player.loc = 2;
}
});
} if(Player.loc == 2) {
nar1.setText("You are now outside");
nar2.setText("the door. What now?");
forward.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
nar1.setText("You hear a guard.");
nar2.setText("What do you do now?");
Player.loc = 3;
}
});
left.addActionListener(new ActionListener() { //Here's another
@Override //assignment to
public void actionPerformed(ActionEvent e) {//the same button
nar1.setText("You hear a guard."); //so when I press
nar2.setText("What do you do now?"); //it here, it
Player.loc = 3; //performs the
} //original assignment
});
right.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
nar1.setText("You hear a guard.");
nar2.setText("What do you do now?");
Player.loc = 3;
}
});
right.setText(rgt);
forward.setText(fwd);
back.setText(bck);
left.setText(lft);
forward.setVisible(true);
} if(Player.loc == 3) {
forward.setVisible(false);
right.setText("Sneak around him!");
left.setText("Fight him!");
}
谢谢你的帮助
比洛夫邦
# 1 楼答案
通过在程序本身中硬编码程序逻辑,将数据与代码混合在一起,这是当前和未来问题的主要根源。这是行不通的,至少如果没有很多麻烦的话
我建议您尝试将您的数据从代码中分离出来,并使您的程序更具MVC风格,它代表Model View Controller(或其众多变体之一)。例如,程序的逻辑由模型控制,其中包括正在探索的土地的非可视化地图、玩家在地图中的位置、他的同伴以及您收集的物品清单。因此,您可能会有几个非GUI类,如Player、Map、Item(这可能是一个接口)、Room等。。。地图本身、可能的项目和位置将在数据文件中指定,可能是简单程序的文本文件,也可能是更复杂程序的数据库,您将需要类来读取和解析此文件
程序的视图就是GUI,它应该尽可能地简单。这里是你的按钮,你的文本显示,如果你喜欢,你的游戏的图形显示。这里没有程序逻辑。没有
控件将是添加到JButtons中的操作侦听器,以及处理用户输入的任何其他代码。但这段代码可能相对简单,它的主要任务是将用户交互传递给模型。例如,如果按下左键,它可能只是
然后,模型将决定如何使用左键按钮(如果有的话)。模型将知道你在游戏中的位置,例如,如果你的左边有一扇门或是一堵墙,并且基于模型的状态,你的游戏将执行必要的操作
# 2 楼答案
匿名内部类侦听器在快速而肮脏的示例代码中看起来不错,但实际上,它们是一个可怕的想法。您正在了解其中一个原因。其他原因是,它们不能通过依赖注入类型的东西轻易地被子类化或修改,不能轻易地被共享(比如按钮、工具栏图标和菜单做同样的事情),不能轻易地被启用/禁用,(比如,“另存为”应该被禁用,因为没有打开)等等
对于这个用例,将它们分解成一系列实际的侦听器,可能组织在一个类、数组或一些枚举中,这样它们就可以进行交换
# 3 楼答案
为什么不把
addActionListener
代码从while循环中提出来呢