ComponentListener example

With this example we are going to see how to use a ComponentListener in order to monitor the window events in our Java Application. This may be useful when you want your application to react differently depending on the position or the kind of movement of the window.

In short, to work with the ComponentListener interface, one should follow these steps:

  • Create a class that implements ComponentListener.
  • Override the methods that correspond to the events that you want to monitor about the window movement e.g, componentHiddencomponentMoved, componentResized, componentShown and customize as you wish the handling of the respective events. Now every time the user interacts with the window, the corresponding method will be executed.
  • Use addComponentListener to add the ComponentListener to the component you wish to monitor.
package com.javacodegeeks.snippets.desktop;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JSplitPane;

public class Component {

    public static void main(String args[]) {

  JFrame jFrame = new JFrame();

  Container cPane = jFrame.getContentPane();

  ComponentListener componenetListener = new ComponentListener() {


public void componentHidden(ComponentEvent event) {

    dump("Hidden", event);



public void componentMoved(ComponentEvent event) {

    dump("Moved", event);



public void componentResized(ComponentEvent event) {

    dump("Resized", event);



public void componentShown(ComponentEvent event) {

    dump("Shown", event);


private void dump(String str, ComponentEvent event) {

    System.out.println(event.getComponent().getName() + " : " + str);



  JButton lbutton = new JButton("Left");



  final JButton lright = new JButton("Right");



  ActionListener action = new ActionListener() {


public void actionPerformed(ActionEvent event) {





  JSplitPane splitBar = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true,

    lbutton, lright);

  cPane.add(splitBar, BorderLayout.CENTER);

  jFrame.setSize(500, 400);


This was an example on how to work with ComponentListener in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button