简体   繁体   中英

Mouse listener doesn't work with interface

I'm puzzled with a strange mouse listener behavior.

First, I defined an interface :

public interface GeniusField {

    public void setEdited(Boolean b);

    public void addMouseListeners();
    public void addKeyListeners();

    public String getStringValue();
}

then, I implement this interface :

public class GeniusComboField extends JComboBox implements GeniusField {

    public GeniusComboField() {

        super();

        //blabla

        addMouseListeners();
        addKeyListeners();

    }

    @Override
    public void addMouseListeners() {
        System.out.println("ADD LISTENTER");

        this.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                System.out.println("mouse mouse");
            }
        });
    }
}

And for some reason, nothing is triggered when I click on my combobox (but I get the "ADD LISTENER" output).

I don't see what is happening.

Can someone help?

In Java Swing JComboBox don't receive the mouse events. It's the components within that do it. Try something like:

for (int i=0; i<this.getComponentCount(); i++) {
    this.getComponent(i).addMouseListener(this);
}

Then make your class implements MouseListener.

Or you can override the method to add object to your combobox and call your addMouseListener() method. Like that each object will have a listener.

JComboBox is a compound component, which means it's made up of two or more other components. You shouldn't register listeners for low-level events on compound components because they wont capture them properly.

You need to implement ActionListener to get it to work.

public class GeniusComboField extends JComboBox implements ActionListener, GeniusField {
   . . .
}

More information about this is available in the swing trail of the Java tutorial.

Somebody has to implement MouseListener( may be GeniusComboField ). something like this.

public class GeniusComboField extends JComboBox implements GeniusField, MouseListener

I tried this code. it seems to work just fine. Problem may be where your adding this combo box. The mouse listener will be for the combo box itself, not the items in it.

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