event

ComponentAdapter example

In this tutorial we are going to see how to use the ComponentAdapter class in Java. In some ways the ComponentAdapter is quite similar to the ComponentListener interface, but being a class it can be used more robustly, among some other features it implements . In this example we are going to see how to monitor the window position of a window in you application.The position of the window will be updated every time the user changes position to the window. This may be useful when you want your application to react differently depending on the position of the window.

In short, to print the window position using the ComponentAdapter, one should follow these steps:

  • Create a class that extends ComponentAdapter class.
  • Override the methods that correspond to the events that you want to monitor about the window movement e.g , componentMoved and customize as you wish the handling of the respective events. Now every time the use moves the window, the corresponding method will be executed.
  • Use the ComponentEvent.getComponent().getX(), ComponentEvent.getComponent().getX() to get the new coordinates of the component that was moved
  • Use addComponentListener(ComponentAdapter adapter) method to add the ComponentAdapter to the component you wish to monitor.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.desktop;

import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JFrame;

public class SimpleAdapterExample {

    public static void main(String[] args) {

  JFrame jFrame = new JFrame();

  jFrame.addComponentListener(new MyAdapter());

  jFrame.setSize(300, 300);

  jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  jFrame.setVisible(true);
    }
}

class MyAdapter extends ComponentAdapter {

    @Override
    public void componentMoved(ComponentEvent e) {

  int x = e.getComponent().getX();

  int y = e.getComponent().getY();

  System.out.println("X: " + x);

  System.out.println("Y: " + y);
    }
}

 
This was an example on how to use the ComponentAdapter class in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron 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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button