简体   繁体   中英

How to force a Jcomponent to appear in Java?

If I have a listener that add JLabel dynamically, is there a way to force the component appear immediately?

I am working on a project that I have an ArrayList storing every dynamically added label. I have another method that involves drawing a line on the panel. It depends on the new JLabel location (x and y). Here is the code inside my listener:

panel.add(labelArrayList.get(index));
panel.repaint();
panel.revalidate();

drawLine();

where drawLine() is a method that simply draws a single line on the panel.

private void drawLine(){
    /*Draw from (x1,y1) to (x2,y2), where (x1,y1) is fixed at original and (x2,y2) is the location of the newly added JLabel*/
    graphics2d.drawLine(x1, y1, x2, y2);
}

When I was in debug mode, I saw the item is not added after repaint() and revalidate() is called. Therefore, I cannot get the location of the newly added Label. The new JLabel appears after the drawLines() method is called.

I want the new label added before the drawLine() is called. Is there any way to make it work?

调用doLayout() (而不是repaint()revalidate() )可以。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM