Anonymous inner class.

In this tutorial we are going to define an anonymous inner class and describe its advantages in the development of code.

In the code below we have two examples as to how to write an anonymous inner class applied to the creation of a listener for the buttons loginButton and registerButton. In both cases, we use only one instruction to define the class and to create the object, saving the code of a complete separate class. In the case of the listener for the registerButton, we also avoid the creation of a variable.

package com.edu4java.swing.tutrial5;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class LoginView3 {

	public static void main(String[] args) {
		JFrame frame = new JFrame("Demo application");
		frame.setSize(300, 150);

	private static void placeComponents(JFrame frame) {

		JLabel userLabel = new JLabel("User");
		userLabel.setBounds(10, 10, 80, 25);

		JTextField userText = new JTextField(20);
		userText.setBounds(100, 10, 160, 25);

		JLabel passwordLabel = new JLabel("Password");
		passwordLabel.setBounds(10, 40, 80, 25);

		JPasswordField passwordText = new JPasswordField(20);
		passwordText.setBounds(100, 40, 160, 25);

		JButton loginButton = new JButton("login");
		loginButton.setBounds(10, 80, 80, 25);

		JButton registerButton = new JButton("register");
		registerButton.setBounds(180, 80, 80, 25);

		ActionListener loginButtonListener = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JButton source = (JButton) e.getSource();
				JOptionPane.showMessageDialog(source, source.getText()
						+ " button has been pressed");
		registerButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog((Component) e.getSource(),
						"button has been pressed");


When we work with user interfaces it is very common to have a lot of listeners which are only used just once for one button, so using this type of anonymous inner classes, will avoid us writing a lot of classes and having useless files in the development of the code.

For more information on anonymous classes, threads and events take a look at Video tutorial: Events. Keyboard input, or even better take a look at the complete series of java game programing.

<< Previous Index >>