在循环中设置JTextField的水平对齐方式

时间:2014-09-13 23:13:57

标签: java swing loops alignment jtextfield

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

      }

   }
 } 

问题:我必须使用随机数创建一个10x10网格并使用JTextField以便我可以在现场更改数字。然后程序必须在矩阵中找到1的最大块(O(n ^ 2)复杂度算法)并将它们突出显示为红色。

尚未实现的是此程序其他部分的侦听器或按钮,以及找到1的最大块的代码。

  

我的问题是如何将文本置于JTextFields的中心?它困扰我,因为我没有为文本字段创建变量名称,但我没有看到我如何使用“.setHorizo​​ntalAlignment(JTextField.CENTER);”

将文本居中放在里面      

如果我确实更改了数字,我也可以为文本字段创建监听器。

如果有帮助,这就是最终程序的样子:

enter image description here

这就是我的程序现在的样子:

enter image description here

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

如果要更改其设置,则必须为文本字段指定变量名称。改变这一行:

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

这些行:

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