Results 1 to 5 of 5
  1. #1
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    63
    Rep Power
    0

    Default GridBagLayout trouble

    I am trying to create a chess game, but am currently facing problems with the overall layout. My MainPanel basically consists of two rows and two columns of labels (a-h in top/bottom rows, 1-8 in leftmost/rightmost columns), and a single panel Chessboard in the center, spanning eight rows and eight columns.
    I decided to use GridBagLayout for this, as it seems the most intuitive choice for such a layout. However, while the Chessboard appears as expected, the label rows and columns do not.


    MainWindow:
    Java Code:
    public class MainWindow {
        public static void main (String[] args) {
            SwingUtilities.invokeLater (new Runnable() {
                public void run() {
                    createGUI();
                }
            });
        }
        
        private static void createGUI() {
            try {
                UIManager.setLookAndFeel (UIManager.getSystemLookAndFeelClassName());
            }
            catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
                e.printStackTrace();
            }
            
            JFrame frame = new JFrame ("Chess");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            
            frame.setContentPane (MainPanel.getInstance());
            
            frame.pack();
            frame.setResizable (false);
            frame.setLocationRelativeTo (null);
            frame.setVisible (true);
        }
    }
    MainPanel:
    Java Code:
    public class MainPanel extends JPanel {
        private static MainPanel instance = new MainPanel();
        private static int PADDING = 20;
        
        private MainPanel() {
            super (new GridBagLayout());
            GridBagConstraints c = new GridBagConstraints();
            
            c.gridwidth = 1;
            c.gridheight = 1;
            c.fill = GridBagConstraints.BOTH;
            
            for (c.gridy = 0; c.gridy <= 9; c.gridy += 9)
                for (c.gridx = 1; c.gridx <= 8; c.gridx++) {
                    JLabel label = new JLabel (Character.toString ((char)('a' + c.gridx - 1)), SwingConstants.CENTER);
                    label.setPreferredSize (new Dimension (Chessboard.SIZE / 8, PADDING));
                    add (label, c);
                }
            
            for (c.gridx = 0; c.gridx <= 9; c.gridx += 9)
                for (c.gridy = 1; c.gridy <= 8; c.gridy++) {
                    JLabel label = new JLabel (Integer.toString (c.gridy), SwingConstants.CENTER);
                    label.setPreferredSize (new Dimension (PADDING, Chessboard.SIZE / 8));
                    add (label, c);
                }
            
            c.gridx = 1;
            c.gridy = 1;
            c.gridwidth = 8;
            c.gridheight = 8;
            add (Chessboard.getInstance(), c);
        }
        
        public static MainPanel getInstance() {
            return instance;
        }
        
        @Override
        public Dimension getPreferredSize() {
            return new Dimension (Chessboard.SIZE + 2 * PADDING, Chessboard.SIZE + 2 * PADDING);
        }
    }
    Chessboard:
    Java Code:
    public class Chessboard extends JPanel {
        public static int SIZE = 480;
        private static Chessboard instance = new Chessboard();
        
        private Chessboard() {
            super();
        }
        
        public static Chessboard getInstance() {
            return instance;
        }
        
        @Override
        public Dimension getPreferredSize() {
            return new Dimension (SIZE, SIZE);
        }
        
        @Override
        public void paintComponent (Graphics g) {
            super.paintComponent (g);
            Graphics2D g2d = (Graphics2D)g;
            int tileSize = SIZE / 8;
            
            for (int i = 0; i < 8; i++) {
                for (int j = 0; j < 8; j++) {
                    reverseColor (g2d);
                    g2d.fillRect (j * tileSize, i * tileSize, tileSize, tileSize);
                }
                reverseColor (g2d);
            }
        }
            
        private static void reverseColor (Graphics g) {
            g.setColor (g.getColor().equals (Color.WHITE) ? Color.BLACK : Color.WHITE);
        }
    }
    What exactly am I doing wrong here? Why is the Chessboard the only component that appears in the MainPanel?

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,025
    Rep Power
    6

    Default Re: GridBagLayout trouble

    For starters, look how many times you create labels inside two nested loops. What you want is to hold x constant for vertical labels
    and y constant for horizontal labels. To lay out labels in a single column or row you only need a single loop.

    Another possible problem is that you are trying to layout labels and also paint in the same panel. It might be easier to create a
    checkerboard component out of a JPanel and simply lay that out in the Grid in the same way you do the labels. The checkerboard
    component would span multiple grids.

    Regards,
    Jim
    Last edited by jim829; 08-04-2014 at 10:18 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    63
    Rep Power
    0

    Default Re: GridBagLayout trouble

    Quote Originally Posted by jim829 View Post
    For starters, look how many times you create labels inside two nested loops. What you want is to hold x constant for vertical labels
    and y constant for horizontal labels. To lay out labels in a single column or row you only need a single loop.
    I'm using a single loop for a single column/row - the inner one. The outer loop simply performs two iterations of the inner loop - one for the leftmost/top column/row, and one for the rightmost/bottom column/row.

    Quote Originally Posted by jim829 View Post
    Another possible problem is that you are trying to layout labels and also paint in the same panel. It might be easier to create a
    checkerboard component out of a JPanel and simply lay that out in the Grid in the same way you do the labels. The checkerboard
    component would span multiple grids.
    Isn't that what I have in my design? I have:
    - the MainPanel component, which is a JPanel on which I'm laying out components (labels + chessboard),
    - the Chessboard component, which is a JPanel with an overridden paintComponent method, to make it paint a chessboard.
    And the Chessboard is then laid out on the MainPanel, much like the labels are, except that the Chessboard spans multiple cells.

    I'm not sure I properly understand what you mean.

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,025
    Rep Power
    6

    Default Re: GridBagLayout trouble

    Sorry, I didn't read your post carefully enough. set your x,y weight constraints to 1. Then make your window resizable. As
    you see the labels appear you will then be able to determine how to adjust them to fit properly.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    63
    Rep Power
    0

    Default Re: GridBagLayout trouble

    I managed to get it to behave properly by setting the weights to 1 and removing the c.fill = BOTH.
    Thanks for your help! :)

Similar Threads

  1. Trouble displaying an image using GridBagLayout
    By treeface99 in forum AWT / Swing
    Replies: 0
    Last Post: 03-15-2012, 10:52 PM
  2. GridBagLayout
    By Moncleared in forum New To Java
    Replies: 1
    Last Post: 10-18-2009, 11:12 PM
  3. GridBagLayout
    By MuslimCoder in forum New To Java
    Replies: 1
    Last Post: 01-15-2009, 09:54 PM
  4. abt gridbaglayout
    By pinky in forum AWT / Swing
    Replies: 1
    Last Post: 12-15-2008, 09:35 AM
  5. GridBagLayout...please help
    By newtojava7 in forum Advanced Java
    Replies: 1
    Last Post: 02-17-2008, 02:16 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •