-1

I'm studying at the moment and I've been given the simple (I thought so) task. I have to make this piece of code to work (I can't modify it):

    JButton b = new JButton("Myszą ciśnij");
    b.addMouseListener ( (MousePressListener) e -> System.out.println("ok"));

I believe MousePressListener should be FunctionalInterface but then, it can't extend MouseListener. Is there any way to work around this issue, or am I approaching it from bad side?

Romen
  • 103
  • 8
  • 1
    See http://stackoverflow.com/questions/25299653/java-idiom-for-lambdas-with-non-sam-interfaces and http://stackoverflow.com/questions/21833537/java-8-lambda-expressions-what-about-multiple-methods-in-nested-class – assylias Oct 27 '15 at 13:52
  • Why not make a random class `Foo` that is not a functional interface, make an interface `Bar` that extends `Foo` that has exactly one abstract method and add the `@FunctionalInterface` annotation to `Bar`? If `Bar` is not a functional interface in Java's eyes it will not compile. – Captain Man Oct 27 '15 at 13:59

1 Answers1

1

addMouseListener expects a MouseListener. MouseListener has multiple abstract methods. Therefore no lambda expression can be of type MouseListener.

I don't know what MousePressListener, but if it's an interface that extends MouseListener, it will still inherit multiple abstract methods from MouseListener, so it can't be a functional interface.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Actually, it can. Managed to do that by making "mouseClicked" abstract, and "mouseEntered", "mouseExited", "mousePressed" and "mouseReleased" default. Thank you for help, though :) – Romen Oct 27 '15 at 18:16