另一个类中的动作监听器 - java

use*_*318 9 java swing listener

它可以有两个类,在一个类似的东西

arrayButtons[i][j].addActionListener(actionListner);
Run Code Online (Sandbox Code Playgroud)

在另一个

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);

                            }

                        }

}
Run Code Online (Sandbox Code Playgroud)

//更多的原因是因为我需要将按钮(swing)与动作监听器分开

我该怎么办?

谢谢

Gor*_*vic 14

不仅可以将这两者分开,还建议(参见MVC模式 - 它非常关于分离屏幕控件,如按钮和程序的逻辑)

我想到的最简单的方法是编写一个实现ActionListener接口的命名类,如下所示:

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
    }

}
Run Code Online (Sandbox Code Playgroud)

然后将其添加到按钮:

ActionListener actionListener = new SomeActionListener(textField1, combo1, textField2);
someButton.addActionListener(actionListener);
Run Code Online (Sandbox Code Playgroud)

  • @user:再次,您可以通过编辑上面的原始帖子提供的详细信息,我们可以提供的信息更多的答案. (2认同)

Mat*_*ogt 6

要回答:"我的问题是动作监听器有很多像摇摆一样的变量,例如,当我换到另一个班级时,我遇到了问题"

您的动作侦听器类可以有一个构造函数,该构造函数接受视图类类型的参数:

public class Listener implements ActionListener {
  private final MyViewClass mView;
  public Listener(MyViewClass pView) {
    mView = pView;
  }

  public void actionPerformed(ActionEvent e) {
    // can use mView to get access to your components.
    mView.get...().doStuff...
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在你看来:

Listener l = new Listener(this);
button.addActionListener(l);
Run Code Online (Sandbox Code Playgroud)