setPreferredSize不起作用 [英] setPreferredSize does not work

查看:261
本文介绍了setPreferredSize不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

import java.awt.Dimension;

import javax.swing.*;

public class Game extends JFrame {
    private static final long serialVersionUID = -7919358146481096788L;
    JPanel a = new JPanel();
    public static void main(String[] args) {
        new Game();
    }
    private Game() {
        setTitle("Insert name of game here");
        setLocationRelativeTo(null);
        setLayout(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        a.setPreferredSize(new Dimension(600, 600));
        add(a);
        pack();
        setVisible(true);
    }
}

因此,我将JPanel的首选大小设置为600 x 600并打包框架,但是框架的大小仍然为0 x0.

So I set the preferred size of the JPanel to 600 by 600 and pack the frame, but the frame's size is still 0 by 0.

这是为什么,我该如何解决?

Why is this and how do I fix it?

推荐答案

如您所说,pack()会尝试排列窗口,以便将每个组件的大小调整为它的preferredSize.

As you said, pack() will try and arrange the window so that every component is resized to its preferredSize.

问题在于布局管理器似乎是一种试图安排组件及其各自的preferredSizes的程序.但是,当您将布局管理器设置为null时,没有人负责.

The problem is that it seems that the layout manager is the one trying to arrange the components and their respective preferredSizes. However, as you set the layout manager as being null, there is no one in charge of that.

尝试注释setLayout(null)行,您将看到结果.当然,对于完整的窗口,您将不得不选择并设置有意义的LayoutManager.

Try commenting the setLayout(null) line, and you're gonna see the result. Of course, for a complete window, you're going to have to choose and set a meaningful LayoutManager.

这对我来说很好:

import java.awt.Dimension;

import javax.swing.*;

public class Game extends JFrame {
    private static final long serialVersionUID = -7919358146481096788L;
    JPanel a = new JPanel();
    public static void main(String[] args) {
        new Game();
    }
    private Game() {
        setTitle("Insert name of game here");
        setLocationRelativeTo(null);
        //setLayout(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        a.setPreferredSize(new Dimension(600, 600));
        add(a);
        pack();
        setVisible(true);
    }
}

这篇关于setPreferredSize不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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