简体   繁体   中英

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:

在此处输入图片说明

This is what my program looks like now:

在此处输入图片说明

Thank you in advance for your help!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM