Home > Blockchain >  Java Swing | The last JTextField doesn't sets to custom size
Java Swing | The last JTextField doesn't sets to custom size

Time:09-22

I'm creating a Word Puzzle Solver. I created for loops to create a JTextField "grid".

enter image description here

When the last field in the lower right corner is created it does not resize to the size I entered. It is resizing to the size of frame.

My code:

public class SolverGUI {

    int sizeOfRect = 50;
    static int height = 5;
    static int width = 5;
    static JTextField[][] textFields = new JTextField[width][height];
    static JFrame frame = new JFrame("Word Puzzle Solver");

    public void createAndShowGUI() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 800);
        createWordPuzzleArea();
        frame.setVisible(true);
    }
    public void createWordPuzzleArea() {
        for (int i = 0; i < height; i  ) {
            for (int i2 = 0; i2 < width; i2  ) {
                textFields[i2][i] = new JTextField();
                frame.add(textFields[i2][i]);
                textFields[i2][i].setBounds(10   (i2 * sizeOfRect), 10   (i * sizeOfRect), sizeOfRect, sizeOfRect);
            }
        }
    }
}

CodePudding user response:

Instead of making the grid yourself, you could make use of enter image description here


And just for the sake of explaining why your code isn't working is that you're fighting the layout manager, I'm getting this output in my computer when running your code:

enter image description here

The way to make it work is to call frame.setLayout(null) which again IS NOT RECOMMENDED, see the second paragraph of this post, if you insist on keep doing it with null-layout you'll just find yourself into more and more troubles as you keep adding features to your program.

After removing the layout manager:

enter image description here

  • Related