Java make Button Enabled

After learning GUI creation through 8 steps, for more command over button event handling, apart this one, another two programs are given – Changing Button Label and Making Button Invisible.

In the following program, three buttons are created with labels Red, Green and Blue. When Red button is clicked, the Blue button is enabled and when Green button is clicked, the enabled button is disabled. That is, Blue button toggles between the states enable and disable.

Concept-wise program is simple, but emphasis should be given to event handling and methods (like setEnabled() and setForeground() etc.) available for Button and how to use them.

Example code on Java make Button Enabled
import java.awt.*;
import java.awt.event.*;
public class ButtonEnabled extends Frame implements ActionListener
{
  Button redBut, greenBut, blueBut;
  public ButtonEnabled()
  {
    setLayout(new FlowLayout());    
   
    redBut = new Button("Red");
    greenBut = new Button("Green");
    blueBut = new Button("Blue");

    redBut.addActionListener(this);
    greenBut.addActionListener(this);
                                // beautification to buttons
    redBut.setForeground(Color.red);
    greenBut.setForeground(Color.green);
    blueBut.setForeground(Color.blue);

    add(redBut); 
    add(greenBut); 
    add(blueBut); 
        
    setTitle("Button Enable Disable");
    setSize(300, 300);
    setVisible(true);
  }
  public void actionPerformed(ActionEvent e)
  {
    Object obj = e.getSource();
    Button btn = (Button) obj;
  
    if(btn == redBut)
       blueBut.setEnabled(true);
    else if(btn == greenBut)
       blueBut.setEnabled(false);
    }
    public static void main(String args[])
    {
      new ButtonEnabled();
    }
}

Java make Button Enabled

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.