我该如何设置我的JFrame在屏幕上的特定位置?我已经设定好了它的大小。我想让它在屏幕上的标准位置上,不被用户移动。
我该如何设置我的JFrame在屏幕上的特定位置?我已经设定好了它的大小。我想让它在屏幕上的标准位置上,不被用户移动。
frame.setResizable(false);
frame.setUndecorated(true);
frame.addComponentListener( new ComponentListener() {
public void componentResized( ComponentEvent e ) {}
public void componentMoved( ComponentEvent e ) {
setLocation( FIX_X, FIX_Y );
}
public void componentShown( ComponentEvent e ) {}
public void componentHidden( ComponentEvent e ) {}
} );
setUndecorated(true)
吧? - Ordous如果你想将位置设置在屏幕中心:
private void centerLocation() throws HeadlessException {
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final Dimension screenSize = toolkit.getScreenSize();
final int x = (screenSize.width - this.getWidth()) / 2;
final int y = (screenSize.height - this.getHeight()) / 2;
this.setLocation(x, y);
}
用户无法移动:
setUndecorated(true);
编辑:
public static final int TOP_LEFT = 0;
public static final int TOP_RIGHT = 1;
public static final int BOTTOM_LEFT = 2;
public static final int BOTTOM_RIGHT = 3;
public void customLocation(int mode) {
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final Dimension screenSize = toolkit.getScreenSize();
int x = 0, y = 0;
switch (mode) {
case TOP_LEFT:
x = 50;
y = 30;
break;
case TOP_RIGHT:
x = (screenSize.width - this.getWidth()) - 50;
y = 30;
break;
case BOTTOM_LEFT:
x = 50;
y = (screenSize.height - this.getHeight()) - 80;
break;
case BOTTOM_RIGHT:
x = (screenSize.width - this.getWidth()) - 50;
y = (screenSize.height - this.getHeight()) - 80;
break;
default:
break;
}
this.setLocation(x, y);
}
而且即使您的框架已经装饰或未装饰,您也可以移动您的框架:
Point initialClick;
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
MouseDragged(evt);
}
});
addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
MousePressed(evt);
}
});
private void MousePressed(java.awt.event.MouseEvent evt) {
initialClick = evt.getPoint();
}
private void MouseDragged(java.awt.event.MouseEvent evt) {
updateLocation(evt);
}
private void updateLocation(MouseEvent evt) {
int thisX = this.getLocation().x;
int thisY = this.getLocation().y;
int xMoved = (thisX + evt.getX()) - (thisX + initialClick.x);
int yMoved = (thisY + evt.getY()) - (thisY + initialClick.y);
int x = thisX + xMoved;
int y = thisY + yMoved;
this.setLocation(x, y);
}
setLocationRelativeTo(null)
呢? - Ordous