Skip to content
Advertisement

Referencing from an inner class

I have the following code

JavaScript

My aim here is to create an array of JTextFields which have a keylistener on. This keylistener should prevent anything other than numbers being entered in the JTextField. It should also change the color of the JTextField’s background if the number entered is not an int. For example 2147483647554. However when I compile this I get the error

Inner class error

So how do I make this so that it is either final or effectively final on all the JTextFields?

Advertisement

Answer

My aim here is to create an array of JTextFields which have a keylistener on. This keylistener should prevent anything other than numbers being entered in the JTextField

The short answer to this is, don’t use KeyListener, it won’t capture the use cases of the user pasting text into the field or if the field is updated programmatically

Instead you want to use a DocumentFilter, for example

JavaScript

See Implementing a Document Filter for more details and DocumentFilter Examples for more examples

It should also change the color of the JTextField’s background if the number entered is not an int

You can do post validation using a InputVerifier, but that might not meet your needs.

This creates a problem. The DocumentFilter, shouldn’t care about the field it’s applied to, but since, it’s doing the validation, it will know when something has gone wrong, so we need some way for the filter to provide notification when the validation fails…

First, we need some callback which tells us when validation has failed or passed…

JavaScript

Then we need to update the filter to raise those notifications based on it’s rules…

JavaScript

Then we need to define our implementation of the ValidationListener to perform the actions we need…

JavaScript

Here, the listener maintains a reference to the field which we want to control

Then we bind it altogether…

JavaScript

Filter

This is all a bit crude, but it gets the basic idea across.

Some improvements might include passing the reference of the DocumentFilter back via the methods of the ValidationListener, you could then use this to lookup the field which triggered the event and update it, reducing the number of handlers you might need to create, for example.

For example

Updated ValidationListener

JavaScript

Updated IntFilter

JavaScript

Example implementation…

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement