Use Component listener to ensure frame visibilities
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
public class Main extends ComponentAdapter {
public void componentMoved(ComponentEvent evt) {
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
int x = evt.getComponent().getX();
int y = evt.getComponent().getY();
if (y < 0 ) {
y = 0;
}
if (x < 0 ) {
x = 0;
}
if (x > size.getWidth() - evt.getComponent().getWidth() ) {
x = (int) size.getWidth() - evt.getComponent().getWidth();
}
if (y > size.getHeight() - evt.getComponent().getHeight() ) {
y = (int) size.getHeight() - evt.getComponent().getHeight();
}
evt.getComponent().setLocation(x, y);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Window cannot be moved to hide part of it");
frame.setSize(300,300);
frame.addComponentListener(new Main());
frame.setVisible(true);
}
}
Related examples in the same category