Home » Desktop Java » awt » event » Print window position example

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of