Search code examples
javaswingjframejtextfield

Need help arranging JTextFields in JFrame


I'm making a Sudoku program in java to learn some algorithms so I want the user to be able to input an unsolved Sudoku puzzle. Here is what I have so far that creates 81 (9x9) boxes:

JTextField input[] = new JTextField[80];
for(int i = 0; i <= 79; i++)
{   
    input[i] = new JTextField();
    input[i].setPreferredSize(new Dimension(30,30));
    f.getContentPane().add(input[i]);
}

When I run this program though all I get is just one input field. I know that all the text fields and initialized, created and added to the jframe. I know you have to mess this the layout but I'm not sure how to do that. Any help is appropriated.


Solution

  • Use a JPanel with GridLayout.

    Also:

    JTextField input[] = new JTextField[80];
    

    That's 80 (not 81) text fields.

    Update: (sample code)

    public class SodokuBoardDemo {
    
        public static void main(String... args) {
            SudokuBoard board = new SudokuBoard();    
            JFrame frame = new JFrame("Sodoku");
            frame.add(board);
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);            
            frame.setVisible(true);
        }
    
        public static class SudokuBoard extends JPanel {
    
            public SudokuBoard() {
                setBorder(BorderFactory.createLineBorder(Color.GRAY));
                setLayout(new GridLayout(3, 3));
                BoardPart input[] = new BoardPart[9];
                for (int i = 0; i < 9; i++) {
                    input[i] = new BoardPart();
                    add(input[i]);
                }
            }
    
            public static class BoardPart extends JPanel {
    
                public BoardPart() {
                    setBorder(BorderFactory.createLineBorder(Color.GRAY));
                    setLayout(new GridLayout(3, 3));
                    JTextField input[] = new JTextField[9];
                    for (int i = 0; i < 9; i++) {
                        input[i] = new JTextField();
                        input[i].setPreferredSize(new Dimension(30, 30));
                        add(input[i]);
                    }
                }
            }
        }
    }