gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:45:33 26 4
gpt4 key购买 nike

   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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com