声明一个变量文本域

declaring a variable textfield

我正在尝试使用变量名声明 JTextField

对于固定的 JTextField,我会在 public class 之后将其简单地声明为

private JTextField HH1;

但是我试图在

中创建可变文本字段
int count = 1
HH + count++ = new JTextField(10);

这是我的私人空间class

private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new GridBagLayout());

GridBagConstraints gbc = new GridBagConstraints();
GridBagConstraints gbc1 = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(5, 50, 5, 0);
gbc1.insets = new Insets(5, -100, 5, 10);
int count = 1;
for(int y = 0; y < 10; y++) {
gbc.gridy = y;
gbc1.gridy = y;
for(int x = 0; x < 1; x++) {
gbc.gridx = x;
gbc1.gridx = x;

vol1HH + count++ = new JTextField(10);
HH1 = new JLabel("HH1");
window.add(HH1 + count++, gbc1);
window.add(vol1HH + count++, gbc);
}    

如何创建名为 HH1 到 HH10 的变量 JTextFields?

在下面回答

private JTextField vol1HH[] = new JTextField [10];

private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new GridBagLayout());


GridBagConstraints gbc = new GridBagConstraints();
GridBagConstraints gbc1 = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(5, 50, 5, 0);
gbc1.insets = new Insets(5, -100, 5, 10);
//int count = 1;
for(int y = 0; y < 10; y++) {
gbc.gridy = y;
gbc1.gridy = y;
for(int x = 0; x < 1; x++) {
gbc.gridx = x;
gbc1.gridx = x;

vol1HH[y] = new JTextField(10); 
window.add(vol1HH[y], gbc);  
}

在您的代码中,您实际上没有遵循声明变量的规则。 变量名不能包含+,变量名也不能是动态的

如果您知道需要多少 JTextField,那么在您的情况下最好的方法是使用 JTextField.

数组
private JTextField HH[] = new JTextField[10];
int count = 0
HH[count++] = new JTextField(10);

如果您不知道需要多少 JTextField,那么使用任何 List 都是个好主意。

private ArrayList<JTextField> HH = new ArrayList<>();
int count = 0;
HH.add(new JTextField(10));