Vivid expression in java not working

I'm trying to make a lambda expresion for an ActionListener, but it gives me an IllegalStart expression, what I'm trying to run so far is as follows:

JFrame frame = new JFrame(); JButton boton = new JButton("Lambda Button"); boton.addActionListener(event -> System.out.println("Hello World!")); frame.add(boton); frame.setVisible(true); 

On the other hand, when I use this code instead:

 JFrame frame = new JFrame(); JButton boton = new JButton("Lambda Button"); boton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Hello World!"); } } ); frame.add(boton); frame.setVisible(true); 

It works great

I initially decided that the problem might be the version of java that I run, but I just update and keep doing the same when I do the java version, I give me the following:

java version java version "1.8.0_45" Java (TM) SE Runtime Environment (build 1.8.0_45-b14) Java client virtual machine HotSpot (TM) (build 25.45-b02, mixed mode)

So, as far as I know, he has a version compatible with the lambda expression, but not succeeding in getting them to work, any ideas or suggestions about what he could do?

EDIT: When I try to compile, I get the following:

 Prueba.java:57: error: illegal start of expression boton.addActionListener(event -> System.out.println("Hello World !")); ^1 error 

EDIT2: I am not using an IDE, im compiling from the command line

+6
source share
3 answers

Edit

According to your comments, you are not using an IDE, and your javac version is 1.7. You need to compile using java 8, otherwise the lambda will not be recognized.


I will keep this part in my answer, as this may solve the problem for someone else, even if it is not a solution in this case.

Your lambda is wonderful. The error is probably due to incorrect compiler level settings.

If you are using eclipse, refer to this post for how to change the compiler compliance level:

How to change the JDK version for an Eclipse project

If you use Netbeans, remember (this is what many people forget) that you need to set source and libraries to 8 if you want it to work correctly.


A source enter image description here


Libraries

enter image description here

Calling java -version from the command line does not mean that the proper library is installed in the IDE, so you need to check this.

If you use any other IDE, then google "How to change the jdk version to YourIDE".

+9
source

And if you use intellij by accident, make sure that the Project language level is set to 8 - Lambdas ..

enter image description here

+5
source

boton.addActionListener (event -> System.out.println ("Hello World!")); - The lambda expression is beautiful. You pass the event to the actionPerformed method of the ActionListener functional interface, which will be displayed when compiling code using the java 8 compiler.

Please check java version.

+2
source

Source: https://habr.com/ru/post/985191/


All Articles