April 1, 2011

Application of Inner Classes in Java - Swing Example

One of the most popular applications of Inner Classes is to handle events in Java to put the event-handling code in a separate event-handing class. This allows separating the event-handling code from the event-generating code. Since the event-handling code is in a separate class, if frees up the event-handling class to inherit from another class.

In the following example code, the class InnerClassExample is the event-generating class (it has JButton object as an instance variable) and the inner class MyEventHandler is the event-handling class (an instance of this class is added to the JButton object as an action listener (or simple, an event-handler).

Since InnerClassExample extends another class, if the InnerClassExample is also implemented as an event-handling class (instead of using an inner class to do the event-handling), it would not be possible to inherit (or reuse) from another class that contains event-handling code.

In the example, MyEventHandler extends TestClass and inherits its methods. The MyEventHandler can then reuse those methods for event-handling. If there was no inner class, then inheriting event-handling code from TestClass would not be possible.

package info.icontraining.basic;

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

public class InnerClassExample extends JFrame  {

   private JButton testButton;
   private JTextArea textArea;
   private JPanel panel;
   public InnerClassExample() {
      panel = new JPanel (new GridLayout(2,1));

      add(panel, BorderLayout.CENTER);
      testButton = new JButton("Test Button");
      testButton.setSize(75, 30);
      MyEventHandler ic = new MyEventHandler();
      textArea = new JTextArea();
      textArea.setSize(100, 50);
      setTitle("Inner Class as Event Handler");

   public class MyEventHandler extends TestClass implements ActionListener {
      public void actionPerformed(ActionEvent ae) {

         // invoke method inherited from Test Class

         if (ae.getSource().equals(testButton)) {
            textArea.setText("Hello World");    

   public static void main(String[] args) {
      InnerClassExample frame = new InnerClassExample();

No comments:

Post a Comment