Why does the JFrame setSize() method not set the size correctly?

后端 未结 6 2087
名媛妹妹
名媛妹妹 2020-12-16 12:40

So I\'ve been programming in java for a semester or so, and I\'ve had this problem a few times and finally got around to asking.

If I make a JFrame and

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-16 13:09

    JFrame SetSize() contains the the Area + Border.

    I think you have to set the size of ContentPane of that

    jFrame.getContentPane().setSize(800,400);
    

    So I would advise you to use JPanel embedded in a JFrame and you draw on that JPanel. This would minimize your problem.

    JFrame jf = new JFrame();
    JPanel jp = new JPanel();
    jp.setPreferredSize(new Dimension(400,800));// changed it to preferredSize, Thanks!
    jf.getContentPane().add( jp );// adding to content pane will work here. Please read the comment bellow.
    jf.pack();
    

    I am reading this from Javadoc

    The JFrame class is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case. For example, to add a child to an AWT frame you'd write:

    frame.add(child);

    However using JFrame you need to add the child to the JFrame's content pane instead:

    frame.getContentPane().add(child);

提交回复
热议问题