Initially I was grabbing a chess but I ran into this problem so I simplified the program to ask the question.
The Program in question is the following:
public class NewClass {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(() -> {
JFrame F = new JFrame("Program");
F.setSize(600,600);
F.setLayout(null);
tab t = new tab();
F.add(t);
t.addLabel(0,new Pawn());
F.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
F.setVisible(true);
});
}
}
class tab extends JPanel
{
JPanel[] squares;
public tab ()
{
squares = new JPanel[4];
setBackground(Color.black);
setBounds(20,20,80,80);
setBorder(BorderFactory.createLineBorder(Color.black, 2));
GridLayout l = new GridLayout(2,2);
l.setHgap(3);
l.setVgap(3);
setLayout(l);
for(int i = 0 ; i< 4;i++)
{
squares[i] = new JPanel();
squares[i].setBackground(Color.white);
squares[i].setLayout(new BorderLayout());
squares[i].setOpaque(true);
add(squares[i]);
}
}
public void addLabel(int s,JLabel l)
{
squares[s].add(l);
}
}
class Pawn extends JLabel
{
public Pawn() {
ImageIcon im = new ImageIcon("/home/jose/Escritorio/pb.png");
this.setIcon(im);
setOpaque(true);
setBackground(new Color(100,200,50,0));
}
}
The Program creates a JPanel (through the tab class) that inside has another 4 JPanel and simulates a 2x2 board, then tab has the addLabel function that allows me to add a peon.
The problem in question occurs when I add these 2 lines of code to the peon
setOpaque(true);
setBackground(new Color(100,200,50,0));
The 2 lines should make the label transparent (for the fourth Color parameter), but apart from that, it also prevents squares [0] from showing its background, showing instead the background of the JPanel container .