如何将JFrame设置为屏幕上的特定位置?我已经设法修复它的大小。我希望它位于屏幕上的标准位置,而不是由用户移动。
答案 0 :(得分:3)
您可以按如下方式修改它:
frame.setResizable(false);
frame.setUndecorated(true);
或者更好:通过添加一个Component侦听器:
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 ) {}
} );
答案 1 :(得分:0)
如果您想在屏幕中心设置位置:
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);
}