Swing: How to place a JFrame N pixels away from the center of the screen first setVisible ()?

What is the code to place the JFrame N pixels (say 300 pixels in the x-direction) away from the center of the screen until setVisible (true) is called?

+3
source share
4 answers

I usually do something like the following to center the JFrame. You can add an offset to the variable wdwLeftas shown in the list to move the frame to the center. (The challenge setPreferredSize()is redundant and only there to do this demo.)

package testapplication;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JFrame;

public class MyJFrame extends JFrame {

    MyJFrame() {
        super("Test");
        Dimension screenSize = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
        setPreferredSize(new Dimension(200, 200));
        Dimension windowSize = new Dimension(getPreferredSize());
        int wdwLeft = 300 + screenSize.width / 2 - windowSize.width / 2;
        int wdwTop = screenSize.height / 2 - windowSize.height / 2;
        pack();   
        setLocation(wdwLeft, wdwTop);
    }

    public static void main(final String [] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                final MyJFrame jf = new MyJFrame();
                jf.setVisible(true);
            }
        }
       );
    }
 }

You can add additional logic to make sure that the offset window is still completely on the screen, as defined getMaximumWindowBounds().

+8

, Frame Javadoc, JFrame setVisible (true) setLocation()

, GraphicsEnvironment.getCenterPoint()

+2

Simple task:

FormName.setLocation(X-Axis Coordinate, Y-Axis Coordinate);
+1
source
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension windowSize = window.getSize();
int windowX = Math.max(0, (screenSize.width  - windowSize.width ) / 2);
int windowY = Math.max(0, (screenSize.height - windowSize.height) / 2);
f.setLocation(windowX, windowY);  // Don't use "f." inside constructor.

                                   OR

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
f.setSize(screenSize.width - 4, screenSize.height - 4);
f.validate();                // Make sure layout is ok
0
source

Source: https://habr.com/ru/post/1722081/


All Articles