I'm building a display API in Java for an internship. Loading in a single image works, but as soon as i want to add another the first image disappears and only draws the second one. Any ideas on how to fix this?
The main class:
package com.lespaul.display;
import java.awt.Graphics;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class Window extends JFrame {
private static final long serialVersionUID = 3716315131567381715L;
public Window() {
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(200, 200);
this.setVisible(true);
Image pane = new Image("floor.png");
Image pane2 = new Image("floor.png");
this.add(pane);
this.add(pane2);
pane2.setPosition(50,50);
this.revalidate();
}
public static void main(String[] args){
Window window = new Window();
}
}
And this is the actual image...
package com.lespaul.display;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import java.awt.image.BufferedImage;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.io.IOException;
import java.net.URL;
import com.lespaul.position.*;
public class Image extends JPanel {
private static final long serialVersionUID = -5815516814733234713L;
public BufferedImage image;
public Vector2 position = new Vector2(0, 0);
public Image() {
}
public Image(String ref){
try {
this.addImage(ref);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setPosition(int x, int y){
Dimension size = this.getPreferredSize();
Insets insets = this.getInsets();
this.setBounds(x+insets.left,y+insets.top,size.width,size.height);
this.position.x = x;
this.position.y = y;
repaint();
}
public void addImage(String fileName) throws IOException {
URL url = this.getClass().getClassLoader().getResource(fileName);
image = ImageIO.read(url);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null)
g.drawImage(image,(int)position.x,(int)position.y, null);
}
}