So I'm playing around with Swing and GUI's, designing a program in which I have a JPanel containing a 10x10 grid of custom JButtons. I have a horizontal index of numbers from 1-10, and a vertical index of letters from A-J (both JLabels).
I used a BorderLayout with the vertical index to the WEST, and an 11x10 GridLayout nested in the CENTER (why? Because that was the easiest way I could think of to perfect the position of the horizontal index numbers above their corresponding columns of buttons).
I have the first 10 spaces of the 110 space grid filled with numbers to index the columns - and this works fine.
I then used a 11x1 grid to equally space the letters on the vertical index to the WEST, to account for the extra slot of the horizontal index on top of the grid (see picture below).
My problem is: whenever I go to fill the empty space at the top of the vertical grid, it places the new JLabel at the bottom, whether it is placed before the fill loop or after.
Here is the result:
And here is the code I used to fill the loop with a JLabel added before and after the fill loop to show how its being placed at the bottom:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test {
private static void createAndDisplayGUI() {
// This panel contains the grid layout for the buttons
JPanel center = new JPanel();
center.setLayout(new BorderLayout());
JPanel gridIndexLeft = new JPanel();
gridIndexLeft.setLayout(new GridLayout(12,1));
gridIndexLeft.add(new JLabel(" " + 0)); // Added a 0 here before fill loop to show where space should be
for (int i=0; i<10; i++) {
gridIndexLeft.add(new JLabel(" " + Character.toString((char)('J' - i))), SwingConstants.CENTER);
}
gridIndexLeft.add(new JLabel(" " + 0)); // And again here with same result
JPanel buttons = new JPanel();
buttons.setLayout(new GridLayout(11,10));
for (int i=0; i<10; i++) {
buttons.add(new JLabel(" " + (10-i)), SwingConstants.CENTER);
}
for (int i=0; i<100; i++) {
buttons.add(new BattleshipButton());
}
center.add(gridIndexLeft, BorderLayout.WEST, SwingConstants.CENTER);
center.add(buttons, BorderLayout.CENTER, SwingConstants.CENTER);
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(center, BorderLayout.CENTER);
JFrame display = new JFrame();
display.setContentPane(content);
display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
display.setBackground(Color.GRAY);
display.setResizable(false);
display.setSize(300,325);
display.setLocation(500,190);
display.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndDisplayGUI();
}
});
}
}
I know the spacing should be 11x1 to match up, but I've made it 12x1 to show what happens when a new JLabel is added before and after the loop.
Any input would be much appreciated!