Home > Mobile >  How to get Java AWT / Swing application x , y coordinates and Height and Width?
How to get Java AWT / Swing application x , y coordinates and Height and Width?

Time:01-10

How do we get the X and Y coordinates and height and width of a java native application created in AWT / Swing framework?

I am trying to get the window object of the AWT/Swing application to get its coordinates.

I have tried adding addWindowListener which will use the windowOpened method. In this WindowEvent I am trying to get the window details.

CodePudding user response:

public void windowOpened(WindowEvent event) {
    Window window = event.getWindow();
    Rectangle rect = window.getBounds();
    System.out.println("x = "   rect.x);
    System.out.println("y = "   rect.y);
    System.out.println("width = "   rect.width);
    System.out.println("height = "   rect.height);
}

Above code prints (for example):

x = 234
y = 234
width = 900
height = 500

CodePudding user response:

JButton button = new JButton();
int x = button.getX();
int y = button.getY();
int width = button.getWidth();
int height = button.getHeight();

CodePudding user response:

Here is the Javadoc for java.awt.Window.

If you are trying to get the area of the window you can draw in you can call getBounds(). This will return a Rectangle object with the Width and Height of the drawable area of the window and the X any Y being the position of the upper-left corner of the window in virtual device coordinates.

If you are trying to find the position and area of a window on the display you can call getGraphicsConfiguration() which will give you a GraphicsConfiguration object repesenting the display device or screen the window is on. You can then call on this object getBounds() to get a Rectangle with the Width and Height of the window and the X any Y being the position of the upper-left corner of the screen in virtual device coordinates.

To locate the window on the screen in screen coordinates you will subtract the X and Y from the GraphicsConfiguration from the X and Y from the Window.

  • Related