获取JFrame内容的实际大小

我得到一个JFrame,我想显示一个带有边框的JLabel,填充可能是50px。 当我将JFrame的大小设置为750,750,并将JLabel的大小设置为650,650并将位置设置为50,50时,它显示出奇怪的…这是我的代码:

public class GUI { /** * Declarate all */ public int height = 750; public int width = 750; Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int x = (screen.width / 2) - (width / 2); // Center horizontally. int y = (screen.height / 2) - (height / 2); // Center vertically. /** * Create the GUI */ JFrame frame = new JFrame(); Border border = LineBorder.createBlackLineBorder(); JLabel label = new JLabel(); public GUI(){ label.setBorder(border); label.setSize(700, 700); label.setLocation(0, 0); frame.getContentPane().setLayout(null); frame.add(label); } public void createGUI() { frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(x,y,width,height); frame.setVisible(true); } } 

所以我认为顶部的标题栏也包含在尺寸中。 在Graphics中,您可以使用getInsets() 。 现在是否有类似Swing / JFrame的东西?

首先得到帧修剪出的像素。

 int reqWidth = reqHeight = 750; // first set the size frame.setSize(reqWidth, reqHeight); // This is not the actual-sized frame. get the actual size Dimension actualSize = frame.getContentPane().getSize(); int extraW = reqWidth - actualSize.width; int extraH = reqHeight - actualSize.height; // Now set the size. frame.setSize(reqWidth + extraW, reqHeight + extraH); 

另一种更简单的方法。 以前的作品,但建议这样做。

 frame.getContentPane().setPreferredSize(750, 750); frame.pack(); 

希望这可以帮助。

编辑:

在将组件添加到框架之前,在构造函数中添加此项。 并将其设置在中间,使用

 frame.setLocationRelativeTo(null); 

这将使窗口居中于屏幕上。

使用setPreferredSize()是有问题的 ,因为它总是以任意选择取代组件的计算。 相反, pack()封闭Window以容纳首选大小的组件,如下所示。

图片

 import java.awt.Color; import java.awt.EventQueue; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; /** * @see https://stackoverflow.com/a/13481075/230513 */ public class NewGUI extends JPanel { private static final int S1 = 10; private static final int S2 = 50; private JLabel label = new JLabel("Hello, world!"); public NewGUI() { label.setHorizontalAlignment(JLabel.CENTER); Border inner = BorderFactory.createEmptyBorder(S1, S1, S1, S1); Border outer = BorderFactory.createLineBorder(Color.black); label.setBorder(new CompoundBorder(outer, inner)); this.setBorder(BorderFactory.createEmptyBorder(S2, S2, S2, S2)); this.add(label); } private void display() { JFrame f = new JFrame("NewGUI"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(this); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new NewGUI().display(); } }); } }