Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Midterm Question - Lamba expressions

+18 votes

Rewite this code using a lamba expression:

JButton button = new JButton("Press Me!");
        button.addActionListener(new ActionListener() {
 
            public void actionPerformed(ActionEvent e)
            {
                System.out.println("You clicked the button");
            }
        }); 
asked Oct 19, 2015 in Fall 15-16 by Michael J. Currie (100 points)

1 Answer

+5 votes
 
Best answer
JButton button = new JButton("Press Me!");

button.addActionListener( (e) -> {

        System.out.println("You clicked the button");

});

answered Oct 20, 2015 by Nelly Cheboi (100 points)
selected Oct 25, 2015 by Michael J. Currie
Do you then have to code the e part in another class or is that being handled by JSwing?
Any parameter that the attached function might use needs to be coded in before the arrow. (->)
the actionPerformed method can use info from the passed in ActionEvent, so it gets passed in basically as a parameter.
For example, if you wanted to print the time that the button was pressed you would call System.out.println(e.getWhen());
I'm not quite sure how it knows the type of object being passed in though.
...