1

I'm trying to make a game of chess, but when I try to insert chess pieces through JLabel icons, they cover the actual chessboard, thus only having the pieces left on screen. How do I make the JLabels not cover up paintings behind it? I'm doing this using a class that extends JApplet.

UPDATE: it worked by using Applet instead of JApplet, though I still have no idea why.

This is the code:

ChessBoard board;   // done in another class file

public static int CEL_WIDTH = 65; 
public static int MARGIN_X = 50, MARGIN_Y = 50;   
    
imagePos = "../src/Schack/Bilder/";

JLabel label; 

public void init() {

    setLayout(null);

    this.setSize(600, 600);
    
    board = new ChessBoard(MARGIN_X, MARGIN_Y, CEL_WIDTH);   
   
    ImageIcon imageIcon = new ImageIcon(getImage(getDocumentBase(), imagePos + "blackRook.png"));  //scaling  my image 
    Image image = imageIcon.getImage(); 
    Image newimg = image.getScaledInstance(CEL_WIDTH, CEL_WIDTH,  java.awt.Image.SCALE_SMOOTH); 
    imageIcon = new ImageIcon(newimg);  

    label = new JLabel(imageIcon);
    label.setBounds(MARGIN_X, MARGIN_Y, CEL_WIDTH, CEL_WIDTH);

    add(label);           
    
}

@Override
public void paint(Graphics g) {
    
    board.paintChessBoard(g);  // another paint method in a different class file 
    
    super.paint(g);
    
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
alice
  • 11
  • 4
  • In your paint method, super.paint(g) should be the first line instead of last. Also, you might want to do the paintComponent method instead of just paint. You would have to change the super call to super.paintComponent(g) as well. – LuckyBandit74 Apr 20 '21 at 17:10
  • You might also benefit from using a JLayeredPane. That way, you could have two separate JPanels for the grid and for the pieces. – LuckyBandit74 Apr 20 '21 at 17:13
  • @LuckyBandit74 it worked through using Applet instead of the JApplet. Thanks for the help though. I did try moving the super.paint(g) command but it resulted in not showing the pieces at all. – alice Apr 20 '21 at 17:18
  • Oh ok, having the super call as the first line is good practice but not sure why it didn’t work in your case. – LuckyBandit74 Apr 20 '21 at 17:19
  • 3
    Applets are dead. You shouldn't be using either Applet or JApplet. Use a JFrame and add components. See: https://stackoverflow.com/questions/6811247/drawing-in-jlayeredpane-over-exising-jpanels/6811800#6811800 for one approach. – camickr Apr 20 '21 at 17:59

0 Answers0