Bavly Hanna
Bavly Hanna

Reputation: 13

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.

Upvotes: 0

Views: 1263

Answers (2)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

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]);
                }
            }
        }
    }
}

Upvotes: 2

posdef
posdef

Reputation: 6532

If you are unsure about how to use different Layouts there is a great tutorial on Oracle documents. If you want to brush up on the components themselves you could also check out the tutorial on them. :)

ps: It might be me being too sleepy but it would appear that you have created 80 text fields not 81.

Upvotes: 1

Related Questions