event

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() {

@Override

public void componentHidden(ComponentEvent event) {

    dump("Hidden", event);

}

@Override

public void componentMoved(ComponentEvent event) {

    dump("Moved", event);

}

@Override

public void componentResized(ComponentEvent event) {

    dump("Resized", event);

}

@Override

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");

  lbutton.setName("Left");

  lbutton.addComponentListener(componenetListener);

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

  lright.setName("Right");

  lright.addComponentListener(componenetListener);

  ActionListener action = new ActionListener() {

@Override

public void actionPerformed(ActionEvent event) {

    lright.setVisible(!lright.isVisible());

}

  };

  lbutton.addActionListener(action);

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

    lbutton, lright);

  cPane.add(splitBar, BorderLayout.CENTER);

  jFrame.setSize(500, 400);

  jFrame.setVisible(true);
    }
}

 
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.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button