+92 332 4229 857 99ProjectIdeas@Gmail.com

Event Handling Using Anonymous Inner Classes (Java)



Event Handling Using Anonymous Inner Classes:

You don’t need to implement any interface with your class, see example below how to use Anonymous inner classes:
Code


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class AnonymousClassExample {
             
              JFrame myFrame = null;
              Container con = null;
              JButton startButton = null;
      
        
      public AnonymousClassExample() {
        
                createComponents();
         }

      public void createComponents() { // initializing GUI interface

         myFrame = new JFrame();
         startButton = new JButton("Hello");
      
         con = myFrame.getContentPane();
         con.setLayout(new FlowLayout());
             
         con.add(startButton);
             
         myFrame.setSize(250,100);
         myFrame.setVisible(true);
         myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           
Here, you can see when the user click on startButton the click event is invoked and will display this message to you:  

        // Handling click event on button using Anonymous inner class
        startButton.addActionListener(new ActionListener() {
                          
              public void actionPerformed(ActionEvent ae) {
                          
                     JOptionPane.showMessageDialog(null, "Hello World!!!!");
              }
       });

Here, you can see when the user close the windows/frame this windowClosing event is invoked and while closing displays this message to you:
  
       // Handling window (Frame) closing event, using Anonymous inner class
       myFrame.addWindowListener(new WindowAdapter() {
                    
              public void windowClosing(WindowEvent we) {
                          
                     JOptionPane.showMessageDialog(null, "Good Bye Cruel World");
              }
       });
      
      
Likewise, if your form/window also contains JTextfield then , you want when i press enter in textfield it should display the text from textfield to messagebox so you would do this:

      // Handling TextField keyPressed Event, using Anonymous inner class
      txtInput.addKeyListener(new KeyAdapter() {
      
          public void keyPressed(KeyEvent ke) {
                 
                 if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
                        
                        JOptionPane.showMessageDialog(null, txtInput.getText());
                 }
          }
          
     });
 
}

0 comments: