Java, JFrame: getWidth() returns 0

前端 未结 2 1543
谎友^
谎友^ 2020-12-18 23:10
setExtendedState(getExtendedState()|JFrame.MAXIMIZED_BOTH);
setResizable(false);
setUndecorated(true);
System.out.println(\"--------> \"+getContentPane().getWidth         


        
相关标签:
2条回答
  • 2020-12-18 23:41

    You haven't realized (i.e. setVisible(true)) the JFrame yet. And therefore, it has no size since it hasn't laid out its components.

    0 讨论(0)
  • 2020-12-18 23:47

    The reason why you got 0 is because you didn't call any of the pack(), setSize(int, int) or setSize(Dimension). This is only when calling one of these method that the layout of your frame will be computed.

    JFrame frame = new JFrame("My Frame");
    frame.setExtendedState(getExtendedState()|JFrame.MAXIMIZED_BOTH);
    frame.setResizable(false);
    frame.setUndecorated(true);
    frame.pack(); // Important line!!! 
    frame.setVisible(true);
    System.out.println("--------> "+getContentPane().getWidth());
    
    0 讨论(0)
提交回复
热议问题