I'm trying to create a chess interface in Java and I'm using a JLayeredPane
to put the pieces on top of my chessboard image. The problem is that the pieces are not added to the layered pane.
This is the code for my DragImage
class (every piece is going to be an instance of this class which you can drag and drop on the chessboard).
class DragImage extends JComponent implements MouseMotionListener {
private static final long serialVersionUID = 1L;
int imageWidth = 52, imageHeight = 52;
int imageX, imageY;
Image img;
public DragImage(Image i) {
img = i;
repaint();
addMouseMotionListener(this);
}
public void mouseDragged(MouseEvent e) {
imageX = e.getX();
imageY = e.getY();
repaint();
}
public void mouseMoved(MouseEvent e) {
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(img, imageX, imageY, this);
}
}
And this is the code for the JPanel
.
The image addresses are correct but they aren't showing up on the panel.
class MyPanel extends JPanel {
private JLayeredPane layeredPane;
private JLabel imageContainer = new JLabel();
private ImageIcon img;
MyPanel() {
super();
img = new ImageIcon("chessboard.png");
this.imageContainer.setIcon(img);
this.layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(416, 416));
layeredPane.add(imageContainer, 50);
imageContainer.setBounds(0, 0, img.getIconWidth(),
img.getIconHeight());
int pozx = 52, pozy = 52;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if(tabla[i][j]!="--"){
DragImage img = new DragImage(Toolkit.getDefaultToolkit().getImage("pieces\\" + tabla[i][j] + ".png"));
//System.out.println("pieces\\" + tabla[i][j] + ".png");
img.setBounds(pozx,pozy,img.imageWidth,img.imageHeight);
layeredPane.add(img,100); //this doesn't work
}
pozx+=52;
}
pozy+=52;
pozx=52;
}
this.add(layeredPane);
}
}
...
frame = new JFrame();
frame.setVisible(true);
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new MyPanel();
frame.add(panel);
frame.pack();