Search code examples
javaswingloopsalignmentjtextfield

Setting the horizontal alignment of JTextField in a loop


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

   public class Excercise24_19 extends JFrame
   {
     private static int[][] grid = new int[10][10]; //creates a grid

   public static void main(String[] args)
   {


     Excercise24_19 frame = new Excercise24_19(); //creates the frame

     frame.setTitle("Excercise 24_19"); //title of window
     frame.setLocationRelativeTo(null); //sets location to middle of screen
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setVisible(true); //displays the window
   }

   public Excercise24_19()
   {
     createMatrix(); //creates matrix of numbers inside "grid"
     setLayout(new GridLayout(10, 10)); //sets a 10 x 10 layout
     String temp; //creates a temp variable to hold number's as string

     for(int i = 0; i < grid.length-1; i++)
     {
       for(int j = 0; j < grid[i].length-1; j++)
         {
           temp = "" + grid[i][j] + "";
           matrix.add(new JTextField(temp, 2));
         }
     }
   }

   public static void createMatrix()
   {
     Random myRand = new Random();
     for(int i = 0; i < grid.length-1; i++)
      {
        for(int j = 0; j < grid.length-1; j++)
        {
          grid[i][j] = myRand.nextInt(2);
        }
  
      }

   }
 } 

PROBLEM: I must create a 10x10 grid with random numbers and use JTextField so that I can change the numbers on the spot. The program must then find the biggest block (Algorithm of O(n^2) complexity) of 1's in the matrix and highlight them red.

Not implemented yet are the listeners or buttons for the other part of this program, and code that finds the largest block of 1's.

My problem is how to i center the text on the JTextFields? Its bothering me because I am not creating variable names for the textfields but I don't see how I am suppossed to center the text inside using ".setHorizontalAlignment(JTextField.CENTER);"

Also will I be able to create listeners for the textfields in case i do change the numbers.

If it helps this is what the end program is suppsed to look like:

enter image description here

This is what my program looks like now:

enter image description here

Thank you in advance for your help!


Solution

  • You have to give the text field a variable name if you want to change its settings. Change this line:

    matrix.add(new JTextField(temp, 2));
    

    to these lines:

    JTextField text = new JTextField(temp, 2));
    text.setHorizontalAlignment(JTextField.CENTER);
    matrix.add(text);