How to get the EXACT middle of a screen, even when re-sized

前端 未结 3 1210
情书的邮戳
情书的邮戳 2020-11-22 16:47

Ok, this sort of have 2 parts of the question.

  1. When I make a JFrame, and draw something on it, even if I make the width 400, and make it so tha

相关标签:
3条回答
  • 2020-11-22 17:06

    This is what I use to centre a JFrame on screen, it simply retrieves the height and width of your monitor, then centres your frame

    public static void moveToCenterScreen(JFrame frame) {
        Toolkit kit = frame.getToolkit();       
        GraphicsDevice[] gs = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
        Insets in = kit.getScreenInsets(gs[0].getDefaultConfiguration());
        Dimension d = kit.getScreenSize();
    
        int max_width = (d.width - in.left - in.right);
        int max_height = (d.height - in.top - in.bottom);   
    
        frame.setLocation((int) (max_width - frame.getWidth()) / 2, (int) (max_height - frame.getHeight() ) / 2);
    }
    
    0 讨论(0)
  • 2020-11-22 17:16

    From the sounds of what you are saying, I think you misunderstand what the dimensions of a normal (decorated) frame include.

    A JFrame consists of a window/frame (normally decorated with a border), a JRootPane, which contains a JLayeredPane which contains the content pane, JMenuBar and glass pane.

    enter image description here

    This is, one of the, reasons why you should never override a top level containers paint method, because you won't actually be painting within the content/view area.

    So, the actual "paintable" region of a frame is it's width - border.width x height - border.height

    enter image description here

    The red line indicates the frame, the blue indicates the content pane.

    This raises a very important question, where's the center of the frame? From the frames perspective, it's 100x100, but from the content pane's perspective, it's 92x81. Depending on what you want, will depend on which value you will use. For positioning the frame, you will want to to use the frames center point, for painting, your will want to use the content panes.

    Now, the easiest way to center a frame on the screen is simply to call Window#setLocationRelativeTo(null) otherwise, I would suggest you use Timr's solution ;)

    0 讨论(0)
  • 2020-11-22 17:29

    You could use something simple along the lines of

    int ___ = (Jframe.getWidth())/2
    int ___ = (Jframe.getHeight())/2
    

    The blank would be the value you want to be at the center point.

    As for the other problem, you could have some padding or something that is moving the item around. Not sure without seeing the code for it.

    0 讨论(0)
提交回复
热议问题