简体   繁体   中英

Add more than one panel on a frame on top of each other

I'm working on a project where I am displaying a square and a circle. The circle moves on its own, but the user moves the square via the arrow keys. Whenever the circle touches the square, it rebounds.

Square and circle are different classes (2 different panels). I want to add those two to a frame, one on top of the other such that both are visible. Can someone tell me how to do so?

JFrame n = new JFrame();
n.setTitle("Background Color for JFrame");
n.setSize(1000,600);
n.setLocationRelativeTo(null);
n.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

n.setResizable(false);

n.add(new Ball());
n.add(new Team());

n.setVisible(true);

User interface components at the same level in a hierarchy are assumed to be non-overlapping by default. You can explicitly work around this by making your components transparent with setOpaque(false) , assuming you are taking care to only draw whats needed in the components, eg in case of a JPanel ensure that its background is not drawn. Its still somewhat random (implementation dependent) which component has precendence over another when doing this.

There is a component explicitly designed for that: JLayeredPane ( https://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html ), which manages "layers" in which components can be put, giving you full control which overlays which.

Games often implement this by themselves, since the full features of JComponent are not needed to represent a simple graphical element. In that case a single component is used as a "canvas" to paint self-defined objects onto making use of an override of paintComponent (See: https://docs.oracle.com/javase/tutorial/uiswing/painting/ )

If you want to do this in swing, as it sounds, I would really recommend making a new class that extends JPanel, and override it's paintComponent method. In this method you use the Graphics in the argument to paint to the canvas. Then you can add this custom panel instead of two separate components to your JFrame, and handle the rendering in there. This render panel can then keep track of all objects that needs to be rendered, preferable implementing some interface (Drawable?) with a draw(Graphics g) method. That way you can make your classes that needs to be rendered implement your Drawable interface, keep then as a list in your render panel and just iterate through them in your paintComponent method and call draw on your Drawables.

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