java - 循环设置JTextField的水平对齐方式

标签 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 block 的代码尚未实现。

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.

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

enter image description here

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

enter image description here

预先感谢您的帮助!

最佳答案

如果您想更改文本字段的设置,则必须为其指定变量名称。更改此行:

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

到这些行:

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

关于java - 循环设置JTextField的水平对齐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25828633/

相关文章:

java - RxJava 中响应式代码和命令式代码之间的错误处理

java - 将 GUI 功能添加到编写 XML 文件的 Java 程序中

java - 非主线程的图片不动

java - 如何使用提交来保存所有查询,如果任何一个查询失败,则不应保存数据

java - 具有基本安全性的 REST Web 服务的 Android 客户端

java - 带图像的 android 按钮

java - 无法更新图像 "JLabel setIcon"

c - 程序挂起,不输出任何东西

javascript - 创建对象数组只进行 1 次迭代

java - 递归输出