Java make Button Enabled


Java make Button Enabled

Three buttons redBut, greenBut and blueBut are created and their foregrounds are changed with setForeground() method. Observe, the blueBut is not linked with ActionListener as it does not have any events to handle in the code.

The button, user interacted, can be known in two ways – by its label or by its object. You have seen in Changing Button Label program to distinguish using label of the button with getActionCommand() method. Now let us distinguish using the button object with getSource() method..

Object obj = e.getSource();
Button btn = (Button) obj;

The getSource() method of ActionEvent class returns the button object, clicked by the user, in the form of Object class. The object obj is explicitly type casted to Button object btn (a super class object, to assign to a subclass object, requires explicit casting). Now the btn object contains the reference of the button clicked by the user which is either redBut or greenBut.

The above two statements can be modified to a single statement by using anonymous object of Object class.

Button btn = (Button) e.getSource();

Programmers prefer the above style only.

blueBut.setEnabled(false);

setEnabled(false) method makes the button blueBut disabled. When a button is disabled, it does not raise any events.

2 thoughts on “Java make Button Enabled”

  1. Object obj = e.getSource();
    Button btn = (Button) obj;

    Why we can not write String str = e.getActionCommand() in this program?
    public void actionPerformed(ActionEvent e)
    {
    if(btn == redBut)
    blueBut.setEnabled(true); else if(btn == greenBut) blueBut.setEnabled(false); } –

Leave a Comment

Your email address will not be published.