Problem Statement:
Write a program the listeners using lambda expressions in Java.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class LambdaListenerTest extends JFrame { public static void main(String args[]) { new LambdaListenerTest(); } private JButton button; public ClickMeLambdaTest() { setTitle("Lambda Expression Test"); button = new JButton("Click Me!"); button.addActionListener(ae -> button1Click()); // lambda expression for ActionListener getContentPane().add(button, BorderLayout.NORTH); setSize(450, 300); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } private int clickCount = 0; public void button1Click() { clickCount++; if(clickCount == 1) button.setText("Clicked!!!"); else button.setText("Clicked " + clickCount + " times!!!"); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.