Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the x and y of a program window in Java?

Is there a way for me to get the X and Y values of a window in java? I read that I'll have to use runtime, since java can't mess directly, however I am not so sure of how to do this. Can anyone point me some links/tips on how to get this?

like image 864
Pedro Cimini Avatar asked May 22 '11 23:05

Pedro Cimini


1 Answers

A little late to the party here but will add this to potentially save others a little time. If you are using a more recent version of JNA then WindowUtils.getAllWindows() will make this much easier to accomplish.

I am using the most recent stable versions as of this post from the following maven locations:

JNA Platform - net.java.dev.jna:jna-platform:5.2.0

JNA Core - net.java.dev.jna:jna:5.2.0

Java 8 Lambda (Edit: rect is a placeholder and will need to be final or effectively final to work in a lambda)

//Find IntelliJ IDEA Window
//import java.awt.Rectangle;
final Rectangle rect = new Rectangle(0, 0, 0, 0); //needs to be final or effectively final for lambda
WindowUtils.getAllWindows(true).forEach(desktopWindow -> {
    if (desktopWindow.getTitle().contains("IDEA")) {
        rect.setRect(desktopWindow.getLocAndSize());
    }
});

Other Java

//Find IntelliJ IDEA Window
Rectangle rect = null;
for (DesktopWindow desktopWindow : WindowUtils.getAllWindows(true)) {
    if (desktopWindow.getTitle().contains("IDEA")) {
         rect = desktopWindow.getLocAndSize();
    }
}

Then within a JPanel you can draw a captured image to fit (Will stretch image if different aspect ratios).

//import java.awt.Robot;
g2d.drawImage(new Robot().createScreenCapture(rect), 0, 0, getWidth(), getHeight(), this);
like image 192
GurpusMaximus Avatar answered Oct 02 '22 14:10

GurpusMaximus