Search code examples
javaoopuser-interfaceactionlistenerencapsulation

Java: Button Encapsulation


So what I am trying to accomplish is to add ActionListener to a button which is defined in another class, without breaking encapsulation of this button.

My GUI class:

public class GUI extends JFrame {  

    private JButton button; 

    public GUI () { 
        this.button = new JButton ();
    }

    public void setText (Text text) {
        this.button.setText (text);
    }

    public JButton getButton () {
        return this.button;
    }    
}

My Game class:

public class Game { 

    private GUI gui;  

    public Game () {
        this.gui = new GUI ();
        this.gui.getButton ().addActionListener (new ActionListener () {
            public void actionPerformed (ActionEvent evt) {
                play ();                       
            }
        });  
    }

    public void play () {
        this.gui.setText ("Play");
    }
}

Then I call a new Game instance in the Main class.

I would like to get rid of the getter in GUI class, otherwise there is no point in using text setter or setters similar to that.

When I add ActionListener to GUI constructor, I have no access to Game methods than. Is there a solution that I don't see?


Solution

  • Let the GUI add the action listener to the button, let the Game create the action listener:

    public class GUI extends JFrame { 
    
        public void addActionListenerToButton(ActionListener listener) {
            button.addActionListener(listener);
        }
    
        ....
    
    }
    
    public class Game { 
    
        private GUI gui;  
    
        public Game () {
            this.gui = new GUI ();
            this.gui.addActionListenerToButton (new ActionListener () {
                public void actionPerformed (ActionEvent evt) {
                    play ();                       
                }
            });  
        }
    
        ...
    }
    

    Alternatively just pass in a functional interface instead of a fully built ActionListener.