JPanel无法使用setSize& setPrefferedSize [英] JPanel not working with setSize & setPrefferedSize

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

问题描述

请解释为什么它不起作用,也可以发布解决方案来解决此问题.提前非常感谢您.

Please explain why it does not work, also could you post a solution to solve this issue. Thank you very mucho in advance.

public class Run extends JFrame{

    /** Fields **/
    static JPanel jpanel;
    private int x, y;

    /** Constructor **/
    public Run() {
        /** Create & Initialise Things **/
        jpanel = new JPanel();
        x = 400; y = 400;

        /** JPanel Properties **/
        jpanel.setBackground(Color.red);
        jpanel.setPreferredSize(new Dimension(20, 30));


        /** Add things to JFrame and JPanel **/
        add(jpanel);

        /** JFrame Properties **/
        setTitle("Snake Game");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setCursor(null);
        setResizable(false);
        setSize(new Dimension(x,y));
        setLocationRelativeTo(null);
        setVisible(true);
    }

    /** Set the Cursor **/
    public void setCursor() {
        setCursor (Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    }

    /** Main Method **/
    public static void main(String [ ] args) {
        Run run = new Run();
        run.setCursor();
    }
}

推荐答案

问题是,JFrame使用BorderLayout,它将尝试调整内容大小以适合父容器.尽管BorderLayout会尝试使用首选大小作为提示,但是如果可用空间更大或更小,它将自动调整以允许中心内容(默认位置)填充父容器的整个可用空间.

The problem is, JFrame uses a BorderLayout, which will try and size the content to fit the parent container. While BorderLayout will try and use the preferred size as a hint, if the available space is greater or less then, it will automatically adjust to allow the center content (the default position) to fill the entire available space of the parent container.

您可以尝试使用FlowLayoutGridBagLayout,这在更多情况下更可能遵循首选大小

You could try using a FlowLayout or GridBagLayout which is more likely to honour the preferred size in more situations

看看如何在容器上布局组件了解更多详情

这篇关于JPanel无法使用setSize& setPrefferedSize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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