简体   繁体   中英

My Output only prints one Rectangle in JAVA

 public static void createAI()
{        
    AI a = new AI(10,10,15,15); 
    frame.add(a);
    AI b = new AI(100,100,15,15);
    frame.add(b);

}

This only shows b; however this prints out a.

 public static void createAI()
{        
    AI a = new AI(10,10,15,15); 
    frame.add(a);
}

Why cant I do both in one method? Thanks for your feedback

The default layout manager for a JFrame is the BorderLayout . When you use the add(...) method without specifying a constraint, then the component is added to the CENTER of the BorderLayout . However, only a single component can be added to the CENTER so only the last component added is displayed.

Try something like:

JPanel panel = new JPanel();
panel.add(a);
panel.add(b);
frame.add(panel);

JPanel uses a FlowLayout by default so now the components should be displayed horizontally.

If that is not the layout you want then read the section from the Swing tutorial on Using Layout Managers for more information and examples.

Probably b is on top of a. Try to invert the sequence of adds, or use the debugger to execute line by line.

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