kie*_* vu 2 java swing location jframe
this.setLocationRelativeTo(null);
Run Code Online (Sandbox Code Playgroud)
jFrame 将显示在屏幕中央。但我不知道如何在屏幕右侧设置 jFrame。
您可以通过根据屏幕和框架的大小计算位置来自己执行此操作。
static void setLocationToTopRight(JFrame frame) {
GraphicsConfiguration config = frame.getGraphicsConfiguration();
Rectangle bounds = config.getBounds();
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(config);
int x = bounds.x + bounds.width - insets.right - frame.getWidth();
int y = bounds.y + insets.top;
frame.setLocation(x, y);
}
Run Code Online (Sandbox Code Playgroud)
屏幕插图包括不应出现窗口的位置,例如任务栏和 Mac 菜单栏。可能有一个操作系统,您可以在屏幕右侧放置一些东西,如果您不减去插图,这会干扰窗口放置。(我认为 Ubuntu 实际上可以做到这一点,但我不记得窗口是放在菜单的顶部还是后面。)
这是一个简单的 MCVE 演示了所有四个边。按四个按钮之一将 锚定JFrame到该边缘。
package mcve;
import javax.swing.*;
import java.awt.*;
public class WindowPlacement {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Window Placement");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton top = new JButton("Top");
JButton left = new JButton("Left");
JButton bottom = new JButton("Bottom");
JButton right = new JButton("Right");
frame.add(top, BorderLayout.NORTH);
frame.add(left, BorderLayout.WEST);
frame.add(bottom, BorderLayout.SOUTH);
frame.add(right, BorderLayout.EAST);
top.addActionListener(e -> setLocationToTop(frame));
left.addActionListener(e -> setLocationToLeft(frame));
bottom.addActionListener(e -> setLocationToBottom(frame));
right.addActionListener(e -> setLocationToRight(frame));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
// Also see:
// https://docs.oracle.com/javase/9/docs/api/java/awt/GraphicsEnvironment.html#getMaximumWindowBounds--
static Rectangle getMaxWindowBounds(JFrame frame) {
GraphicsConfiguration config = frame.getGraphicsConfiguration();
Rectangle bounds = config.getBounds();
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(config);
bounds.x += insets.left;
bounds.y += insets.top;
bounds.width -= insets.left + insets.right;
bounds.height -= insets.top + insets.bottom;
return bounds;
}
static void setLocationToTop(JFrame frame) {
frame.setLocation(frame.getX(), getMaxWindowBounds(frame).y);
}
static void setLocationToLeft(JFrame frame) {
frame.setLocation(getMaxWindowBounds(frame).x, frame.getY());
}
static void setLocationToBottom(JFrame frame) {
Rectangle bounds = getMaxWindowBounds(frame);
frame.setLocation(frame.getX(), bounds.y + bounds.height - frame.getHeight());
}
static void setLocationToRight(JFrame frame) {
Rectangle bounds = getMaxWindowBounds(frame);
frame.setLocation(bounds.x + bounds.width - frame.getWidth(), frame.getY());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4566 次 |
| 最近记录: |