Print window position example

In this example we are going to see how to use a ComponentListener in order to print the window position in a Java 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, 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 , componentMoved and customize as you wish the handling of the respective events. Now every time the user moves the window, the corresponding method will be executed.
  • Use the Event.getComponent().getX(), Event.getComponent().getX() to get the new coordinates of the component that was moved
  • Use addComponentListener to add the ComponentListener to the component you wish to monitor.

Let’s take a closer look at the code snippets that follow:

package com.javacodegeeks.snippets.desktop;

import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

import javax.swing.JFrame;

public class WidowPosition extends JFrame implements cc {

    public WidowPosition() {


  setSize(410, 300);





    public void componentResized(ComponentEvent event) {

    public void componentMoved(ComponentEvent event) {

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

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

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

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

    public void componentShown(ComponentEvent event) {

    public void componentHidden(ComponentEvent event) {

    public static void main(String[] args) {

  new WidowPosition();

This was an example on how to use a ComponentListener to print the position of a window 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