可以有两个类,并且在一个类似的类中
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 )与 Action 监听器分开
我该怎么做?
谢谢
最佳答案
不仅可以将这两者分开,而且还推荐这样做(请参阅 MVC 模式 - 这在很大程度上是关于将按钮等屏幕控件与程序逻辑分开)
我想到的最简单的方法是编写一个实现 ActionListener
接口(interface)的命名类,如下所示:
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 - 另一个类中的 Action 监听器 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4985507/