How to Get the X and Y of a Program Window in Java

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

To get the x and y position of "any other unrelated application" you're going to have to query the OS and that means likely using either JNI, JNA or some other scripting utility such as AutoIt (if Windows). I recommend either JNA or the scripting utility since both are much easier to use than JNI (in my limited experience), but to use them you'll need to download some code and integrate it with your Java application.

EDIT 1
I'm no JNA expert, but I do fiddle around with it some, and this is what I got to get the window coordinates for some named window:

import java.util.Arrays;
import com.sun.jna.*;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.win32.*;

public class GetWindowRect {

public interface User32 extends StdCallLibrary {
User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class,
W32APIOptions.DEFAULT_OPTIONS);

HWND FindWindow(String lpClassName, String lpWindowName);

int GetWindowRect(HWND handle, int[] rect);
}

public static int[] getRect(String windowName) throws WindowNotFoundException,
GetWindowRectException {
HWND hwnd = User32.INSTANCE.FindWindow(null, windowName);
if (hwnd == null) {
throw new WindowNotFoundException("", windowName);
}

int[] rect = {0, 0, 0, 0};
int result = User32.INSTANCE.GetWindowRect(hwnd, rect);
if (result == 0) {
throw new GetWindowRectException(windowName);
}
return rect;
}

@SuppressWarnings("serial")
public static class WindowNotFoundException extends Exception {
public WindowNotFoundException(String className, String windowName) {
super(String.format("Window null for className: %s; windowName: %s",
className, windowName));
}
}

@SuppressWarnings("serial")
public static class GetWindowRectException extends Exception {
public GetWindowRectException(String windowName) {
super("Window Rect not found for " + windowName);
}
}

public static void main(String[] args) {
String windowName = "Document - WordPad";
int[] rect;
try {
rect = GetWindowRect.getRect(windowName);
System.out.printf("The corner locations for the window \"%s\" are %s",
windowName, Arrays.toString(rect));
} catch (GetWindowRect.WindowNotFoundException e) {
e.printStackTrace();
} catch (GetWindowRect.GetWindowRectException e) {
e.printStackTrace();
}
}
}

Of course for this to work, the JNA libraries would need to be downloaded and placed on the Java classpath or in your IDE's build path.

How to get the center x and y of desktop with swing

How would I get the center coordinate of the computer monitor running the swing application?

You can get the center coordinate with java.awt.Toolkit:

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int centerX = screenSize.width/2;
int centerY = screenSize.height/2;

However, you don't need it.

Just use:

yourFrame.setLocationRelativeTo(null);

And it will be automatically centered

Where do X and Y start at in swing windows

All containers have their own coordinate context, this means that 0x0 is the top/left corner of the container itself, irrelevant of where it's placed in its parent container.

I am trying to center a JLabel at the top of an 800x600 JPanel

Then use an appropriate layout manager and avoid all the oddities of font metrics, DPI and rendering pipelines which exists across all other systems/OSs

Centered Simply

(This example will also adapt to changes in the screen size, and you've not had to do a thing, bonus)

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

public TestPane() {
setLayout(new GridBagLayout());
add(new JLabel("I'm in the middle"));
}

@Override
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}

}

}

at the top of

Whoops, might have misread that /p>

In that case, you could do something like...

public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.anchor = GridBagConstraints.NORTH;
add(new JLabel("I'm in the middle"), gbc );
}

Another option might be to use a BorderLayout

public TestPane() {
setLayout(new BorderLayout());
JLabel label = new JLabel("I'm in the middle");
label.setHorizontalAlignment(JLabel.CENTER);
add(label, BorderLayout.NORTH);
}

which might simplify the layout, as you'd need to use a seperate component for the CENTER position instead

See Laying Out Components Within a Container for more details

But I have to manual position the component because of reasons ....

99.9% of time, when you think you need to do "absolutely positioning", you don't. You just need to gain a better understanding of the available layout managers and how and when to use them.

That 0.1% of time you really need "absolutely positioning", you probably don't either, you probably just need a custom layout manager to fill that one edge case (maybe consider MigLayout)

Laying out components effectively is complex process with many, many decisions needing to be made and variable states to take into account. An entire API has been provided to you to solve this issue, you are wasting your own time, and everyone elses, but not taking advantage of it

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

To get the x and y position of "any other unrelated application" you're going to have to query the OS and that means likely using either JNI, JNA or some other scripting utility such as AutoIt (if Windows). I recommend either JNA or the scripting utility since both are much easier to use than JNI (in my limited experience), but to use them you'll need to download some code and integrate it with your Java application.

EDIT 1
I'm no JNA expert, but I do fiddle around with it some, and this is what I got to get the window coordinates for some named window:

import java.util.Arrays;
import com.sun.jna.*;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.win32.*;

public class GetWindowRect {

public interface User32 extends StdCallLibrary {
User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class,
W32APIOptions.DEFAULT_OPTIONS);

HWND FindWindow(String lpClassName, String lpWindowName);

int GetWindowRect(HWND handle, int[] rect);
}

public static int[] getRect(String windowName) throws WindowNotFoundException,
GetWindowRectException {
HWND hwnd = User32.INSTANCE.FindWindow(null, windowName);
if (hwnd == null) {
throw new WindowNotFoundException("", windowName);
}

int[] rect = {0, 0, 0, 0};
int result = User32.INSTANCE.GetWindowRect(hwnd, rect);
if (result == 0) {
throw new GetWindowRectException(windowName);
}
return rect;
}

@SuppressWarnings("serial")
public static class WindowNotFoundException extends Exception {
public WindowNotFoundException(String className, String windowName) {
super(String.format("Window null for className: %s; windowName: %s",
className, windowName));
}
}

@SuppressWarnings("serial")
public static class GetWindowRectException extends Exception {
public GetWindowRectException(String windowName) {
super("Window Rect not found for " + windowName);
}
}

public static void main(String[] args) {
String windowName = "Document - WordPad";
int[] rect;
try {
rect = GetWindowRect.getRect(windowName);
System.out.printf("The corner locations for the window \"%s\" are %s",
windowName, Arrays.toString(rect));
} catch (GetWindowRect.WindowNotFoundException e) {
e.printStackTrace();
} catch (GetWindowRect.GetWindowRectException e) {
e.printStackTrace();
}
}
}

Of course for this to work, the JNA libraries would need to be downloaded and placed on the Java classpath or in your IDE's build path.

Using the coordinate plane in the JFrame

Here the Co-ordinates start from the TOP LEFT SIDE of the screen, as as you increase value of X, you will move towards RIGHT SIDE, though as you increase the value of Y, you will move DOWNWARDS. Here is a small example Program for you to understand this a bit better, simply click on it anywhere.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DrawingExample
{
private int x;
private int y;
private String text;
private DrawingBase canvas;

private void displayGUI()
{
JFrame frame = new JFrame("Drawing Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

canvas = new DrawingBase();
canvas.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
text = "X : " + me.getX() + " Y : " + me.getY();
x = me.getX();
y = me.getY();
canvas.setValues(text, x, y);
}
});

frame.setContentPane(canvas);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new DrawingExample().displayGUI();
}
});
}
}

class DrawingBase extends JPanel
{
private String clickedAt = "";
private int x = 0;
private int y = 0;

public void setValues(String text, int x, int y)
{
clickedAt = text;
this.x = x;
this.y = y;
repaint();
}

public Dimension getPreferredSize()
{
return (new Dimension(500, 400));
}

public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString(clickedAt, x, y);
}
}


Related Topics



Leave a reply



Submit