Search code examples
javaswing

Avoiding this escape in Swing component initialization


In more recent Java the linting error possible 'this' escape before subclass is fully initialized comes up a lot in Swing code. For example, calling AbstractAction.putValue() from the ctor.

    public class PauseAction extends AbstractAction {
        private TrackModel model;

        public PauseAction(TrackModel model) {
            this.model = model;
            putValue(NAME, "Pause");
            // Bunch of other possible keys
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            model.pause();
        }
    }

Is it a fool's errand to try and avoid this warning?


Solution

  • I would use the factory pattern here

    public class PauseAction extends AbstractAction {
        private TrackModel model;
    
        private PauseAction(TrackModel model) {
            this.model = model;
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            model.pause();
        }
    
        public static Action createPauseAction(TrackModel model) {
            PauseAction result = new PauseAction(model);
            result.putValue(NAME, "Pause");
            // Bunch of other possible keys
            return result;
        }
    }