簡體   English   中英

如何在ActionListener的其他類中使用方法?

[英]How do I use a method in a different class in ActionListener?

當我按下JButton button1 ,我需要在另一個類中調用dropPoison方法。 我該怎么做呢?

主班

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;

public class Main extends JFrame implements ActionListener {
  private boolean PoisonTrue;
  private Player player1;
  private Player activePlayer;
  private boolean player1Poison;

  public Main() // creating the Frame
  {
    // code
  }

  public void actionPerformed(ActionEvent evt) {
    if (evt.getSource() instanceof TokenButton) {

      TokenButton button1 = (TokenButton) evt.getSource();

      if (PoisonTrue == true) {
        if (this.activePlayer == player1) {
          // Call dropPoison here
          player1Poison = true;
          PoisonTrue = false;
        }
      }
    }
  }
}

令牌按鈕類

import java.awt.Color;
import java.util.ArrayList;

import javax.swing.JButton;

public class TokenButton extends JButton {

  ArrayList<Cell> cells;

  int nxtToken;

  TokenButton[] buttons;

  Grid gridPanel;

  public TokenButton() {
    nxtToken = 19;
    cells = new ArrayList<Cell>();
  }

  public int dropToken(Player player) {
    if (this.nxtToken != -1) {
      // code
    }

    return nxtToken;
  }

  public void dropPoison(Cell selectedCell, Grid grid) {
    int x = 0;
    int y = 0;
    this.gridPanel = grid;

    int xAxis = selectedCell.getXPosition();
    int yAxis = selectedCell.getYPosition();

    // North
    if (yAxis > 0) {
      grid.gridCells[x][y - 1].setBackground(Color.BLACK);
      grid.gridCells[x][y].setBackground(Color.GREEN);
    }
  }
}

在Main類中使用button1事件時,需要調用dropPoison方法。

因此,不要像使用instanceof來測試Button那樣,而是要做類似的事情。

  • 在您的JFrame中創建一個按鈕。
  • 向JButton實例注冊一個動作偵聽器。
  • 做您的工作嗎?執行(即致電dropPoison)
  • 將JButton添加到JFrame。

您違反了許多以這種方式編寫的OO約定。 建立以下示例:

public class Parent {
    private JFrame myFrame;
    public Parent() {
        myFrame = new JFrame();
        JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            @Override 
            public void actionPerformed(ActionEvent theEvent) {
                call drop poison here or whatever method you need to call
            }
        });
        frame.add(button, BorderLayout.CENTER);  
    }

    public static void main(String[] args) {
        new Parent();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM