加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – JPanel不使用setSize和setPrefferedSize

发布时间:2020-12-14 05:50:14 所属栏目:Java 来源:网络整理
导读:请解释为什么它不起作用,也可以发布解决方案来解决这个问题.非常感谢你提前. public class Run extends JFrame{ /** Fields **/ static JPanel jpanel; private int x,y; /** Constructor **/ public Run() { /** Create Initialise Things **/ jpanel = new
请解释为什么它不起作用,也可以发布解决方案来解决这个问题.非常感谢你提前.
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将尝试使用首选大小作为提示,但如果可用空间大于或小于,则它将自动调整以允许中心内容(默认位置)填充父容器的整个可用空间.

您可以尝试使用FlowLayout或GridBagLayout,它更有可能在更多情况下遵循首选大小

有关详细信息,请查看How to layout components on containers

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读