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 theComponentAdapter
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.