How to add 2 JComponent to JPanel at the same place stretched on full JPanel? I tryed to:
add(ship,null);
add(ground,null);
How to add 2 JComponent to JPanel at the same place stretched on full JPanel? I tryed to:
add(ship,null);
add(ground,null);
I'm guessing as to your use case, but is "ground" a background image containing JPanel? If so, then add it in such a way so that it fills the container, perhaps via BorderLayout.CENTER with the container using BorderLayout of course.
The ship, I'm guessing is a sprite that is drawn on the background. If so, consider having it not be a JPanel but rather a logical object that holds an image Sprite that can be drawn in the ground's paintComponent method.
As always the devil will be found in the details. You first.
Edit
You state in comment:
Stage is my background and it extends JPanel. Ship is a player element (JComponent). Ground (JComponent) is something which player can't touch. I wanted to have this two elements (ground and ship) like layers where the image is drawn. I need to have one point reference to check collisions.
I assume that you have a paintComponent(Graphics g)
override method in your Stage object where you draw your background image.
Based on this assumption, I change my previous recommendation in that I feel that neither ground nor ship should extend JPanel since you don't really need for them to do this. You already have a JPanel on which you can do your drawing and game interaction, so why create more when they'll only clutter things up? The only exception I see is if either ground or ship need to hold other components, and if so, then yes, they should extend JPanel.
Consider:
draw(Graphics g)
method that draws their respective images at the x an y location when called and passed a valid Graphics instance.paintComponent(Graphics g)
method draw both instances by calling their respective draw methods.Edit 2
You now ask:
One more question: When should i have keyListener?
I recommend that you not use a KeyListener.
KeyListener is a low-level construct, and in general you should prefer to use higher-level constructs such as Key Bindings as they are safer and easier to use without causing side effects or having problems. For instance, it is easy to run into problems with focus issues if you use a KeyListener since it only works if the component listened to has the focus. This is easily circumvented if you used key bindings instead.