![](/img/trans.png)
[英]i want to make my actionlistener on a separete class but it doesnt seem to work
[英]I want to use an object in my ActionListener Class
我正在尝试实现我的打牌游戏中的纸牌游戏代码。 我在ActionListener类中使用Deck时遇到问题。 Deck是Deck类的一个对象,具有ArrayList和一些从Deck中选择一张卡片的方法作为变量/实例(我不知道正确的术语)。actionlistener类的代码如下:
class Play implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
Card a1, a2, b1, b2;
a1 = Deck.pickCard(Deck.Deck);
String Player2="Player2";
String Player1="Player1";
int score1=0;
int score2=0;
System.out.println(Player1 + " drew a " + a1.getName(a1) + " of " + a1.getType(a1));
a2 = Deck.pickCard(Deck.Deck);
System.out.println(Player1 + " drew a " + a2.getName(a2) + " of " + a2.getType(a2));
b1 = Deck.pickCard(Deck.Deck);
System.out.println(Player2 + " drew a " + b1.getName(b1) + " of " + b1.getType(b1));
b2 =Deck.pickCard(Deck.Deck);
System.out.println(Player2 + " drew a " + b2.getName(b2) + " of " + b2.getType(b2));
if (a1.getValue(a1) + a2.getValue(a2) > b1.getValue(b1) + b2.getValue(b2)) {
score1 = score1 + 1;
System.out.println(Player1 + " win and has " + score1 + " points");
}
if (a1.getValue(a1) + a2.getValue(a2) < b1.getValue(b1) + b2.getValue(b2)) {
score2 = score2 + 1;
System.out.println(Player2 + " win and has " + score2 + " points");
}
}
}
如果我在Play
类中设置了Deck
类的构造函数,则代码将正常运行,但是每次Deck重新创建且拾取的卡不会从Deck中移除。 当我输入这个问题时,我记得分数也在刷新。我尝试将这段代码放入方法中并尝试在Play类中调用该方法,但这似乎也不起作用,我的文字带有下划线用红色表示a non static method cannot be referenced from a static context
。 我一般都不是编程新手,而关于继承和变量的这些问题现在看来太尴尬和奇怪。 我想问一下是否有可能解决这种问题,因为我已经为练习的前一部分做了很多工作。在此先感谢您!
我不确定您的确切情况是什么,但也许您需要让Play的构造函数接受Deck作为参数:
class Play implements ActionListener {
Deck deck;
public Play(Deck deck) {
this.deck = deck;
}
@Override
public void actionPerformed(ActionEvent ae) {
...
}
}
现在您可以执行addActionListener(new Play(deck));
并为Play提供对您的Deck的参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.