获取JFrame内容的实际大小 [英] Get the real size of a JFrame content

查看:52
本文介绍了获取JFrame内容的实际大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I get a JFrame and i want to display a JLabel with a border in it with a padding of maybe 50px. When i set the size of the JFrame to 750, 750, and the size of the JLabel to 650, 650 and the location to 50, 50, it display it strange... Here's my code:

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);
    }

}

因此,我认为顶部的标题栏也包含在大小中.在图形"中,您可以使用 getInsets().现在,Swing/JFrame有类似的东西吗?

So I think the title-bar at the top is also include in the size. In Graphics you can use getInsets(). Now is there anything like that for Swing / JFrame?

推荐答案

首先获取由帧修剪的像素.

First get the pixels trimmed out by the frame.

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);

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

An alternate simpler way. The previous works but this is recommended.

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

希望这会有所帮助.

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

Add this in your constructor before adding components to the frame. and to set it in the middle, use

frame.setLocationRelativeTo(null);

这将使窗口在屏幕上居中.

This will center the window on the screen.

这篇关于获取JFrame内容的实际大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆