另一个类中的动作监听器 - java [英] action listener in another class - java
本文介绍了另一个类中的动作监听器 - java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以有两个类,其中一个类似
it is possible to have two class, and in one something like
arrayButtons[i][j].addActionListener(actionListner);
和另一个
ActionListener actionListner = new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int j = 0; j < arrayButtons.length; j++) {
for (int i = 0; i < arrayButtons[j].length; i++) {
if (arrayButtons[j][i] == e.getSource()) {
if ((gameNumber == 2) && (playHand.getNumberOfCards() == 0)) {
if (player[j].getCard(i).getSuit() == Suit.HEARTS.toString() && player[j].hasSuitBesideHearts())
//second game
messageOnTable("xxx");
else{
arrayButtons[j][i].setVisible(false);
test[j].setIcon(player[j].getCard(i).getImage());
pnCardNumber[j].setText(Integer.toString(player[j].getCard(i).getNumber()));
pnCardName[j].setText(player[j].getCard(i).toString());
pnCardSuit[j].setText(player[j].getCard(i).getSuit());
playHand.addCard(player[j].getCard(i), j);
player[j].removeCard(i);
}
}
}
//以及更多
的原因是因为我需要将按钮(swing)与动作监听器分开
//and more the reason of that is because i need to separate the button (swing) to the action listener
我是怎么回事可以吗?
谢谢
推荐答案
不仅可以将这两者分开,也建议(参见MVC模式 - 它非常关于分离屏幕控件,如按钮和程序的逻辑)
Not only it is possible to separate these two, it's also recommended (see MVC pattern - it's very much about separating screen controls like buttons, and the logics of your program)
最简单的方法来我的想法是编写一个实现 ActionListener
接口的命名类,如下所示:
The easiest way that comes to my mind is to do write a named class that implements ActionListener
interface, something like this:
public class SomeActionListener implements ActionListener{
private JTextField textField1;
private JComboBox combo1;
private JTextField textField2;
//...
public SomeActionListener(JTextField textField1, JComboBox combo1,
JTextField textField2){
this.textField1=textField1;
this.combo1=combo1;
this.textField2=textField2;
//...
}
public void actionPerformed(ActionEvent e) {
//cmd
}
}
然后将其添加到按钮:
ActionListener actionListener = new SomeActionListener(textField1, combo1, textField2);
someButton.addActionListener(actionListener);
这篇关于另一个类中的动作监听器 - java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文