JFrame: get size without borders?

后端 未结 4 379
渐次进展
渐次进展 2020-12-03 13:40

In Java, is it possible to get the Width and Height of the JFrame without the title and other borders?

frame.getWidth() and frame.getHeight()1 seems to return the wi

4条回答
  •  眼角桃花
    2020-12-03 14:17

    This works fine

    frame.getContentPane().getSize();
    

    But not if you haven't added content yet. In my case, I wanted to calculate the inner dimensions of the JFrame before adding content, so I could divide up the content accordingly. Here's what I came up with.

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    
    pack(); // Need this, otherwise insets() show as 0.  
    int scrW = (int)screenSize.getWidth();
    int scrH = (int)screenSize.getHeight();
      int innerW = scrW - getInsets().left - getInsets().right;
      int innerH = scrH - getInsets().top - getInsets().bottom;
    
      // Need to setSize(), otherwise pack() will collapse the empty JFrame
      setSize(scrW, scrH);
    

提交回复
热议问题