0

I have three classes: One is the main:

public class Thera {
    public static void main(String[] args) {
        TheraGUI start = new TheraGUI();
    }

}

One is the GUI

public class TheraGUI extends JFrame {
    public TheraGUI(){
        Board board = new Board();
        this.setLayout(new GridBagLayout());
        this.setTitle("Thera");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
        this.add(board);
        this.pack();
    }
}

And last is my board:

package thera;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class Board extends JPanel {
  JLayeredPane layeredpane;
  JPanel board;
  JLabel piece;
  int xAdj;
  int yAdj;
  private static final String imageFolderPath = "src/resources/images/";
  Dimension dimension = new Dimension(500, 500);

  public Board(){
      //create the layered pane  
      layeredpane = new JLayeredPane();
      layeredpane.setPreferredSize(dimension);
      this.add(layeredpane);

  //create the Board
  board = new JPanel();
  board.setLayout(new GridLayout(7,9));
  board.setPreferredSize(dimension);

  layeredpane.add(board, JLayeredPane.DEFAULT_LAYER);

  for(int c = 0; c < 7; c++){
      for(int r = 0; r < 9; r++){
          JPanel square = new JPanel(); 
          square.setLayout(new BorderLayout());
          square.setBackground(new Color(255, 204, 051));
          board.add(square);
      }
  }

 } 

}

My problem: my board won't appear! Additional info: the primary layout is a gridbaglayout, and in cell one i added a JPanel, inside the JPANel i added a layeredpane.

user3266210
  • 299
  • 4
  • 15
  • 1
    1) For better help sooner, post a [MCTaRE](http://stackoverflow.com/help/mcve) (Minimal Complete Tested and Readable Example). 2) See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) – Andrew Thompson Mar 10 '14 at 10:31

2 Answers2

0

You're adding a component (thus changing the hierarchy) after the setting the visibility. Swing is kinda pedantic about how things work.

public class TheraGUI extends JFrame {
    public TheraGUI(){
        Board board = new Board();
        this.setLayout(new GridBagLayout());
        this.setTitle("Thera");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // note the order
        this.add(board);
        this.pack();
        this.setVisible(true);
    }
}
Gorbles
  • 1,169
  • 12
  • 27
0

A layered pane uses a null layout which means you are responsible for setting the size/location of components added to the layered panel:

board.setPreferredSize(dimension);
board.setSize(dimension); // added

Note you should not be hardcoding preferred sizes. You should be creating a class to represent your squares and then override the getPreferredSize() method of that class.

camickr
  • 321,443
  • 19
  • 166
  • 288