declaring a variable textfield

141 views Asked by At

I am trying to declare a JTextField with a variable name

For a fixed JTextField i would simply declare it after my public class as

private JTextField HH1;

but with a variable text field i am trying to create them within

int count = 1
HH + count++ = new JTextField(10);

this is within my private 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);
}    

How can i create the variable JTextFields called HH1 to HH10?

Answer below

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

There are 1 answers

3
afzalex On BEST ANSWER

In your code you are actually not following the rules to declare a variable. A variable name cannot contain +, and neither the name of a variable could be dynamic.

If you know how many JTextField you will need then in your case the best approach will be to use array of JTextField.

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

And if you don't know how much JTextField you will need then to use any List will be a good idea.

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