Search code examples
javafocuslistener

Java adding constants to dynamicly added code


is it possible to add a constant to code added to an object? So if my psudo code below where run then the object in question gained focus what ever value was in ZZZ at the time would be printed out?

public void addStupidListener(JTextField textField, String ZZZ) {
    textField.addFocusListener(new FocusListener() {

        @Override
        public void focusGained(FocusEvent e) {
            System.out.println("selected" + ZZZ);
        }

        @Override
        public void focusLost(FocusEvent e) {
            System.out.println("de-selected" + ZZZ);
        }
    });
}

Solution

  • In general you can capture stack variables in Anonymous classes. Here's an example. I assume what you are trying to do will work.

    public class AnonymousTest {
    
    
        public static void main(String[] args){
    
            Object obj = someObject("Hey world!");
            System.out.println(obj);
        }
    
        public static Object someObject(String str){
            return new Object(){
                public String toString(){
                    return super.toString()+str;
                }
            };
        }
    }
    

    Output: stackoverflow.AnonymousTest$1@7f31245aHey world!