user3679182 user3679182 - 5 months ago 15
Java Question

How can I call a method with parameter mouse event e in another class?

I write the code below and want to call the mousepress method in another class, but I get the error to define parameter mouseevent for where I called it, but I get

NullPointerException
error when I define a variable mouseevent
e
.

Please help me.

public void mousePressed(MouseEvent e , int tankid) {
System.out.println("insert which tanks you want to move");
JButton clicked = (JButton)e.getSource();
System.out.println(clicked.getAlignmentX()+"mmmmmmmmmmm");
for(int x = 0; x<board.r; x++)
{
for(int y = 0;y<board.cc;y++)
{
if(clicked == board.squares[x][y])
{

ImageIcon icon = new ImageIcon("C:/Users/win_10/Desktop/tanks/tank1.png");
board.squares[troops[tankid].getPosition().x][troops[tankid].getPosition().y].setIcon(null);
board.squares[x][y].setIcon(icon);
map.mapboard[troops[tankid].getPosition().x][troops[tankid].getPosition().y].setBackground(null);
troops[i].getPosition().x = x;
troops[i].getPosition().x = y;
map.mapboard[troops[tankid].getPosition().x][troops[tankid].getPosition().x].add(new JLabel(name));
SwingUtilities.updateComponentTreeUI(map.getContentPane());
System.out.println(x + " "+ y);
}
}
}
}

Answer

Here is a short demo that may help get you started. Basically you create the listener in the class that need to respond to the mouse click (Moo) and add it to a component in the class which generates the mouse event:

import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Foo extends JFrame {

    private JButton btn;

    Foo(){

        super("Foo frame");
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(200,100));
        setLocationRelativeTo(null);

        btn = new JButton("Click Me");
        getContentPane().add(btn);

        validate();
        pack();
    }

    JButton getBtn() {
        return btn;
    }

    public static void main(String[] args)  {

        Foo foo = new Foo();
        Moo moo = new Moo();
        foo.getBtn().addMouseListener(moo.getMouseListener());
        foo.setVisible(true);
    }
}

class Moo {

    Moo() {}

    MouseListener getMouseListener() {

        return new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {

                System.out.println("Mouse pressed ! ");
            }
        };
    }
}

If you need more clarifications don't hesitate to ask.

Comments