Reputation: 201
I'm trying to create a basic game where a character can move an image on the screen, which is on top of a background image. Here is my main method, where I'm setting all of this up:
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Stuff");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
// Create a panel with a component to be moved
JPanel character = new JPanel();
JLabel component = new JLabel();
component.setIcon(new ImageIcon("C:/Users/Cory/Desktop/img/eagle.jpg"));
component.setSize( component.getPreferredSize() );
component.setLocation(200, 200);
component.repaint();
JButton left = addMotionSupport( component );
character.add(component);
character.repaint();
//end moveable
frame.add( character );
frame.repaint();
JPanel background = new JPanel();
JLabel contentPane = new JLabel();
contentPane.setIcon(new ImageIcon("C:/Users/Cory/Desktop/img/background.png"));//sets contentPane to display the background
contentPane.setSize(contentPane.getPreferredSize());
background.add(contentPane);
background.repaint();
frame.add(background);
frame.repaint();
//frame.add(left, BorderLayout.SOUTH);
frame.setSize(1000, 800);
frame.setVisible(true);
}
});
}
The issue I'm running into is the following. I am able to display the background image OR the moveable image, but not both. What I believe is happening is that the two jpanels are 'overlapping' on top of each other - is this correct? How would I fix something like this? I browsed through the API a bit and I found something called a JLayeredPane, but I'm not sure how to use that and if it is even the correct tool. Any insight you provide would be most appreciated.
N.B. the 'addMotionSupport' method only adds a KeyListener to the passed argument.
Upvotes: 0
Views: 94
Reputation: 324098
a character can move an image on the screen, which is on top of a background image.
Then you need to add the character to the background.
So the basic code should be:
JLabel character = new JLabel(...);
character.setSize( character.getPreferredSize() );
JLabel background = new JLabel(...);
background.add( character );
frame.add( background );
You don't need the extra panels. You can add a label directly to the frame.
You need to set the size of the character label because a JLabel does not use a layout manager. So in this case you are responsible for managing the size and location of the character when you add it to the background component. The location will default to (0, 0);
You don't need all the frame.repaint()
statements, the frame will be painted when it is made visible. Don't use frame.setSize(), instead use frame.pack(). Then the frame will be set to the size of the background image.
Upvotes: 2