user3021153
user3021153

Reputation: 35

Make a 10x10 board using java swing

I'm trying to make a 10x10 board with java swing. But i don't know why one of the box is out of the place. The other 99 grid is on place as i set in setBounds(), but the last grid is in 0,0 position. i'm using jButton as a grid. Any hints of what i am doing wrong? the code i write so far :

JFrame frame = new JFrame();
JButton[][] grid;
int y = 10;
int x = 10;
public Board() {
    initComponents();
    jButton = new JButton[x][y];
    setGrid();
}
private javax.swing.JButton[][] jButton;
public void setGrid(){
    int size = 75;
    int o = size * x;
    int p = size * y;

    int k = 0;
    int l = 0;
    int z = 9;
    for(int i=p;i>0;i-=size){
        for(int j=0;j<o;j+=size){
            jButton[k][l] = new javax.swing.JButton();
            jButton[k][l].setBounds(j, i, size, size);
            jButton[k][l].setBackground(Color.yellow);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);

            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jButton[k][l])
                    )

            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addComponent(jButton[k][l])
                    ));
            if(k==9){
                k=0;
            }
            else{
                k++;
            }
        }l++;
     }   
}

public static void main(String[] args){
    JFrame frame = new JFrame("Board");
    frame.setContentPane(new Board());
    Dimension dmsn = new Dimension();
    dmsn.height = 1080;
    dmsn.width = 1920;
    Insets insets = frame.getInsets();
    frame.setMinimumSize(dmsn);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

Upvotes: 0

Views: 2071

Answers (1)

Sage
Sage

Reputation: 15418

for(int i=p;i>0;i-=size){
        for(int j=0;j<o;j+=size){
            jButton[k][l] = new javax.swing.JButton();
            jButton[k][l].setBounds(j, i, size, size);
            jButton[k][l].setBackground(Color.yellow);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
  1. You are creating a new layout each time the loop gets executed. Put the setLayout code before the loop.
  2. Don't set bounds while working layout other than the NULL layout
  3. Use GridLayout when you intend to make your Container to be grid.
  4. Don't use GroupLayout while hand coding: working with it is not impossible but, tedious.

Upvotes: 2

Related Questions