问题描述:

 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.

相关阅读:
Top