1

I have a tricky task to do in Java. I have to react on mouseclick with the code passed as lambda expression (print 'ok' on console) The problem is that I cannot modify Main class, I have to prepare class/interface to receive lambda expression. I tried to follow tutorials on Lambda expressions but I keep getting error about using non functional interface. Main:

import javax.swing.*;

public class Main {

  public static void main(String[] args) {
    SwingUtilities.invokeLater( ()-> {
        JFrame f = new JFrame();
        JButton b = new JButton("Mouse Click");
        b.addMouseListener ( (MousePressListener) e -> System.out.println("ok") );
        f.add(b);
        f.pack();
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setVisible(true);
      }
    );
  }
}

Could you guys with more experience could help me with some advice how could I start working with this problem? I started with creating a class but then I got lost ( I did this class and used 'implements' so right now type MousePressListener is also type MouseListener right?)

public class MousePressListener implements MouseListener {

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub

    }

}
jawjaw
  • 147
  • 1
  • 11

1 Answers1

4

Instead of a class use an interface with default methods for everything except mouseClicked:

@FunctionalInterface
public interface MousePressListener extends MouseListener
{
  @Override
  default public void mouseEntered(final MouseEvent e) {
  }

  @Override
  default public void mouseExited(final MouseEvent e) {
  }

  @Override
  default public void mousePressed(final MouseEvent e) {
  }

  @Override
  default public void mouseReleased(final MouseEvent e) {
  }
}

So now MousePressListener is an interface with just one non-default method as required for a functional interface. This can be used without changing your Main class at all.

greg-449
  • 109,219
  • 232
  • 102
  • 145