DasherJava / src / dasherJava / gui / DefaultLocationJFrame.java
DefaultLocationJFrame.java
Raw
package dasherJava.gui;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class DefaultLocationJFrame extends JFrame {
	
	//This class contains a workaround for an issue that is probably caused by a Java bug (tested on Manjaro Linux
	//with XFCE desktop and Java 17.0.12+7): When using setLocationByPlatform(true) to make the frame appear in the
	//center of the screen instead of the top left corner when it is opened for the first time, it is placed as
	//expected, but the x and y fields of the frame stay at (0, 0), breaking placement of sub-dialogs and making
	//global mouse input return incorrect results (because it believes that the frame is at (0, 0), while it actually
	//is somewhere else). Fortunately, there is an easy workaround available: The location fields apparently get
	//updated on every state change of the frame, so we initially minimize (iconify) it and then restore it to normal
	//state when it is opened for the first time.
	
	private boolean alreadyRestored = false;
	
	public DefaultLocationJFrame(String title) {
		super(title);
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowOpened(WindowEvent e) {
				if (alreadyRestored) return; //already done, don't need to do this again when the
				                             //frame is closed and re-opened
				setExtendedState(JFrame.NORMAL);
				alreadyRestored=true;
			}
		});
		setLocationByPlatform(true);
		setExtendedState(JFrame.ICONIFIED);
	}
}