Blaine
Blaine

Reputation: 342

how to impliment mouse listener

Kind of a noob question, but then again, I am a noob. I'm trying to implement a sort of "universal" mouse listener. That is, when I click any of the objects on screen, it runs a specific amount of code. I have the current solution below, but the code I want to run is the same for 10 different objects, so this gets rather tedious.

        difference2 = new JLabel(new ImageIcon("transparent.png")); 
        difference2.setBounds(645,490,10,10); //left, top, width, height
        contentPane.add(difference2);
        difference2.setVisible(true);
        difference2.addMouseListener(new MouseAdapter()
            {
                public void mouseClicked(MouseEvent e) {
//code
}
            });

I am aware I can create a separate method such as the following

public void mouseClicked(MouseEvent e) {
        JOptionPane.showMessageDialog(null,"this would be nice");
    }

But I can't figure out how to set up a mouse listener on every object for it. The JOptionPane currently does nothing.

Upvotes: 1

Views: 179

Answers (2)

Akunosh
Akunosh

Reputation: 237

I might have misread your question, but if you want the same mouselistener on various objects,you could store the instance of your listener in a variable once and then add it to whatever gui object you want it added to.

MouseListener ml = new MouseListener() {
    @Override
    public void mouseReleased(MouseEvent e) {//code}

    @Override
    public void mousePressed(MouseEvent e) {//code}

    @Override
    public void mouseExited(MouseEvent e) {//code}

    @Override
    public void mouseEntered(MouseEvent e) {//code}

    @Override
    public void mouseClicked(MouseEvent e) {//code}
};

JLabel j1 = new JLabel("Label1");
j1.addMouseListener(ml);
JLabel j2 = new JLabel("Label2");
j2.addMouseListener(ml);

Upvotes: 2

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26946

You can create an instance of an anonymous class that extends MouseAdapter and assign it to a variable that you can reuse (myMouseListener in this case):

MouseListener myMouseListener = new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        JOptionPane.showMessageDialog(null,"this would be nice");
    }   
};

difference2.addMouseListener(myMouseListener);
aSecondObject.addMouseListener(myMouseListener);
aThirdObject.addMouseListener(myMouseListener);
...

Upvotes: 2

Related Questions