1

I am making a Sudoku board GUI which should look like this one http://www.sudoku.4thewww.com/Grids/grid.jpg

For some reason it is only showing the last 3*3 board. If someone could tell me what I am doing wrong I would greatly appreciate it thanks.

import java.awt.*;
import java.util.Random;
import java.awt.*; 
import java.awt.event.*;
import javax.swing.*;

public class gui2 extends JFrame{

private JTextField f[][]= new JTextField[9][9] ;
private JPanel p[][]= new JPanel [3][3];

public gui2(){
    super("Sudoku");
    setLayout(new GridLayout());

    for(int x=0; x<=8; x++){
        for(int y=0; y<=8; y++){
            f[x][y]=new JTextField(1);
        }
    }

    for(int x=0; x<=2; x++){
        for(int y=0; y<=2; y++){
            p[x][y]=new JPanel(new GridLayout(3,3));
        }
    }
    setLayout(new GridLayout(3,3,5,5));

for(int u=0; u<=2; u++){
    for(int i=0; i<=2; i++){    
        for(int x=0; x<=2; x++ ){
            for(int y=0; y<=2; y++){
            p[u][i].add(f[y][x]);
            }
        }
        add(p[u][i]);
    }
}



}

}
user2737810
  • 21
  • 1
  • 7

1 Answers1

1

This code should work:

public class Gui2 extends JFrame{

    /**
     * 
     */
    private static final long serialVersionUID = 0;
    private JTextField f[][]= new JTextField[9][9] ;
    private JPanel p[][]= new JPanel [3][3];

    public Gui2(){
        super("Sudoku");

        for(int x=0; x<=8; x++){
            for(int y=0; y<=8; y++){
                f[x][y]=new JTextField(1);
            }
        }

        for(int x=0; x<=2; x++){
            for(int y=0; y<=2; y++){
                p[x][y]=new JPanel(new GridLayout(3,3));
            }
        }

        setLayout(new GridLayout(3,3,5,5));

        for(int u=0; u<=2; u++){
            for(int i=0; i<=2; i++){    
                for(int x=0; x<=2; x++ ){
                    for(int y=0; y<=2; y++){
                        p[u][i].add(f[y+u*3][x+i*3]);
                    }
                }
            add(p[u][i]);
            }
        }
    }
}

The problem was in this line: p[u][i].add(f[y][x]);. You are adding the same 9 text fields over and over to every panel, but a Component that is added more then once is removed from the previous container. This line p[u][i].add(f[y+3*u][x+3*i]); takes the current panel position into consideration, and uses the entire JTextField array.

Elist
  • 5,313
  • 3
  • 35
  • 73
  • Thank you for the help, but what is the "serialVersionUID" for? – user2737810 Sep 28 '13 at 23:40
  • Sure :) See [This](http://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it). You might need to generate a fresh one if you decide to use [`Serialization`](http://en.wikipedia.org/wiki/Serialization). – Elist Sep 28 '13 at 23:43