Get location of a swing component

前端 未结 6 1295
野的像风
野的像风 2021-01-18 03:19

I have put some JPanels into another JPanel which its\' layout is Box Layout and Y-Axis. After I have put all the panels I need to get the Y position of each added JPanel in

6条回答
  •  青春惊慌失措
    2021-01-18 04:15

    The problem is often that the layout or the drawing is done only after the whole method returned. In that case, getX and getY return 0.

    It may help to call pack() on the frame window, or doLayout() or validate() on the JPanel you are working on. But often it doesn't help, because you have little influence on the internal scheduling: http://www.oracle.com/technetwork/java/painting-140037.html

    What does help me in this case is to put the part where I need the X and Y location into a worker thread:

    JPanel panelHolder = new JPanel(new BoxLayout(this, BoxLayout.Y_AXIS));
    for(int i = 0; i< 10; i++){
        JPanel p = new JPanel(); 
        panelHolder.add(p);
    }
    
    int componentCount = panelHolder.getComponentCount();
    
    SwingUtilities.invokeLater(new Runnable() {         
        @Override
        public void run() {
            for (int j = 0; i < componentCount; j++) {    
                Component c = pnlRowHolder.getComponent(i);
                JPanel p = (JPanel) c;
                System.out.println(p.getY());
            }
        }
    });
    

    This way getting the X and Y will be postponed until the layout is done.

提交回复
热议问题