Passing a function name to a function

Chilcix :

Hopefully I phrased the question right. So, I am working on a program that has a UI and utilizes buttons. I have a couple of things that need to be done with the buttons. These get handled by a function when the buttons get pressed

Example of buttons:

private void columnOneButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                
    buttonDisable(0);
}                                               

private void columnTwoButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                
    buttonDisable(1);
} 

And the function:

private void buttonDisable(Integer index){
    // deleted code where the index does stuff, that works fine and didn't want to show it

    this.columnOneButton.setEnabled(false);

}

Clearly this will only work for columnOneButton, so to fix it I used the index like so:

private void buttonDisable(Integer index){
// deleted code where the index does stuff, that works fine and didn't want to show it

        if(index == 0){
        this.columnOneButton.setEnabled(false);
        } else if(index == 1){
        this.columnTwoButton.setEnabled(false);
        } // .... there are more than two buttons
}

While this gets the job done, it is wrong and I want to acheive the same thing by passing a second parameter in, I was thinking like this:

private void buttonDisable(Integer index, String buttonName){
// deleted code where the index does stuff, that works fine and didn't want to show it

this.buttonName.setEnabled(false);

}

This obviously doesn't work, but I want it to and can't figure out how to.

Thank you!

Cường Lư Quốc :

You can use that:

public void actionPerformed(ActionEvent e) {
    buttonDisable(1, (JButton) e.getSource());
}

private void buttonDisable(Integer index, JButton button){
    button.setEnabled(false);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=20843&siteId=1