AGEM
AGEM

Reputation: 217

ActionListener for an array of JTextFields

I want to center the content of the JTextField based on its content.

     for(int i=0; i<10; i++){                                   
           txtFields[i] = new JTextField(20); 

           txtFields[i].addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    txtFields[i].setHorizontalAlignment(JTextField.CENTER);
                }
            });
        }

I am getting error, local variable i cannot be accessed within innerclass.

Upvotes: 0

Views: 665

Answers (3)

splungebob
splungebob

Reputation: 5425

Why the ActionListener at all? Perhaps I'm misunderstanding your requirement, but won't this do what you're looking for:

for (int i=0; i<10; i++)
{                                   
  txtFields[i] = new JTextField(20);
  txtFields[i].setHorizontalAlignment(JTextField.CENTER);
}

Upvotes: 1

Marc Baumbach
Marc Baumbach

Reputation: 10473

This is because the variable i is not available in the scope that actionPerformed is called. A simple fix would be to declare a final variable in the for loop's scope:

for (int i = 0; i < 10; i++) {    
    final JTextField currentField = new JTextField(20);                               
    txtFields[i] = currentField;
    txtFields[i].addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
             currentField.setHorizontalAlignment(JTextField.CENTER);
         }
    });
}

Or:

for (int i = 0; i < 10; i++) {                             
    txtFields[i] = new JTextField(20);
    txtFields[i].addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
             ((JTextField) e.getSource()).setHorizontalAlignment(JTextField.CENTER);
         }
    });
}

Personally, I'd suggest you create an ActionListener subclass that accepts a JTextField in its constructor. It's a cleaner approach and helps reduce confusing defects like the one you encountered.

Upvotes: 4

gcvt
gcvt

Reputation: 1512

Just before the "addActionListener" statement write "final int j = i;", and then use "j" within the inner class.

Upvotes: 1

Related Questions