简体   繁体   中英

How do I use a method in a different class in ActionListener?

When I press the JButton button1 , I need the dropPoison method to be called in another class. How do I do this?

Main Class

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

Token Button Class

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

I need the dropPoison method to be called when in the Main class I use button1 event.

So, instead of testing for Buttons with instanceof , do something like this.

  • Create a button in your JFrame.
  • Register an Action Listener with the instance of the JButton.
  • Do your work in actionPerformed (ie call dropPoison)
  • Add the JButton to the JFrame.

You are breaking a lot of OO conventions writing it this way. Build off the example below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM