如何将JFrame放在TOP_RIGHT上?
我知道中心,左上角是正常的,但是如何放入右上角?
答案 0 :(得分:6)
作为this answer: positioning to the bottom-right的示例,我进行了调整以使其显示在右上角
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TopRightFrame {
private void display() {
JFrame f = new JFrame("Top-Right Frame");
f.add(new JPanel() {
@Override // placeholder for actual content
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
});
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice defaultScreen = ge.getDefaultScreenDevice();
Rectangle rect = defaultScreen.getDefaultConfiguration().getBounds();
int x = (int) rect.getMaxX() - f.getWidth();
int y = 0;
f.setLocation(x, y);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new TopRightFrame().display();
}
});
}
}
答案 1 :(得分:0)
您可以在以下代码中修改现有的JFrame构造函数粘贴:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice defaultScreen = ge.getDefaultScreenDevice();
Rectangle rect = defaultScreen.getDefaultConfiguration().getBounds();
int x = (int) rect.getMaxX() - this.getWidth();
int y = 0;
this.setLocation(x, y);
this.setVisible(true);
即。所以它看起来像这样:
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice defaultScreen = ge.getDefaultScreenDevice();
Rectangle rect = defaultScreen.getDefaultConfiguration().getBounds();
int x = (int) rect.getMaxX() - this.getWidth();
int y = 0;
this.setLocation(x, y);
this.setVisible(true);
}