event

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

  c(this);

  setSize(410, 300);

  setLocationRelativeTo(null);

  setDefaultCloseOperation(EXIT_ON_CLOSE);

  setVisible(true);

    }

    @Override
    public void componentResized(ComponentEvent event) {
    }

    @Override
    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);
    }

    @Override
    public void componentShown(ComponentEvent event) {
    }

    @Override
    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.
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