【问题标题】:Setting the horizontal alignment of JTextField in a loop在循环中设置 JTextField 的水平对齐方式
【发布时间】:2014-11-07 20:00:36
【问题描述】:
   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);”将文本居中。

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

如果有帮助,最终程序应该是这样的:

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

提前感谢您的帮助!

【问题讨论】:

  • matrix.add(new JTextField(temp, 2));这行有一个错误,因为你没有定义matrix
  • 取出我添加了一个名为矩阵的框架的行。我取出框架,直接将它们添加到 Excercise24_19()
  • 无论你做什么,你的代码都不会编译。
  • 对我有用,我将为解决的代码提供编辑。

标签: java swing loops alignment jtextfield


【解决方案1】:

如果你想改变它的设置,你必须给文本字段一个变量名。更改此行:

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

到这些行:

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

【讨论】:

  • 我之前尝试过,但我想我在修复随机生成器后没有尝试过!谢谢!
猜你喜欢
  • 2013-04-18
  • 1970-01-01
  • 2019-08-24
  • 2012-06-12
  • 2019-04-22
  • 2015-07-09
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
相关资源
最近更新 更多