Search code examples
javaswingjpaneljlabeljlayeredpane

Cannot see the contents in the JLayeredPane in a JPanel


I am trying to create a board class that extends JPanel for a backgammon game and a JLayeredPane to create a dragging area for my checkers but i cant even print a simple rectangle to the panel. It does print the image but not the JLabel. Here is my JPanel class

public class BoardPanel extends JPanel{

private JLayeredPane lp;

private BufferedImage imageBoard;
private final int WIDTH = 1000;
private final int HEIGHT = 800;

private ArrayList<Slot> slotSet1;
private ArrayList<Slot> slotSet2;
private ArrayList<Slot> slotSet3;
private ArrayList<Slot> slotSet4;
private CheckerSet ch1;
public  Checker chc;

public BoardPanel(){

    initComponents();

}

private void initComponents(){

    lp = new JLayeredPane();

    setPreferredSize(new java.awt.Dimension(1500, 1000));

    //lp.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
    lp.setBorder(javax.swing.BorderFactory.createTitledBorder("asdadsaddadsadasdadsa"));
    lp.setMaximumSize(new java.awt.Dimension(1124, 904));
    lp.setMinimumSize(new java.awt.Dimension(1124, 904));


    try {
       imageBoard = ImageIO.read(getClass().getResource("/images/board.jpg"));
   } catch (IOException e) {
       System.out.println("file error");
   }

        JLabel label = new JLabel();
        label.setVerticalAlignment(JLabel.TOP);
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setOpaque(true);
        label.setBackground(Color.BLACK);
        label.setForeground(Color.black);
        label.setBorder(BorderFactory.createLineBorder(Color.black));
        label.setBounds(0, 0, 50, 50);

    lp.add(label,JLayeredPane.DEFAULT_LAYER);


}
public void paintComponent(Graphics g){

    //g.drawImage(imageBoard,0,0,null);

}

}

And there is the main

 public static void main(String[] args){

    JFrame f = new JFrame();

    //GamePanel gp = new GamePanel();
    BoardPanel gp = new BoardPanel();

    f.add(gp);

    //f.getContentPane().add(gamePanel);
    f.setSize(new Dimension(1500, 1000));
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

How can i resolve it? Thanks guys


Solution

  • You will have to add a Layout to your JLayeredPane, like a GridLayout for example. Try this:

    GridLayout gl = new GridLayout(20, 21);
    lp.setLayout(gl);
    

    after initializing lp. Then you can add all components that you Need to the GridLayout, for instance lp:

    gl.add(lp)
    

    The Layout will manage how the things will be displayed; in this case, it will fill the grid from the GridLayout, first the first row (of which 20 exist), then the second one and so on (I don't think you actually Need 20 rows, it is just like that in my example code)