Java Changing Button Label

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

In this program, the same button label toggles between Bharath and India. When Bharath is clicked, the button label changes to India and when India is clicked, the label changes to Bharath. Concept-wise program is simple, but emphasis should be given to event handling and methods (like setLabel() and getLable()) available in Button and how to use them.

Example on Java Changing Button Label
import java.awt.*;
import java.awt.event.*;
public class ButtonLabel extends Frame implements ActionListener
{
  Button changeBut;
  public ButtonLabel()
  {
    changeBut = new Button("Bharath");
    changeBut.addActionListener(this);
                                      // beautification to changeBut
    changeBut.setBackground(Color.pink);
    changeBut.setForeground(Color.blue);
    changeBut.setFont(new Font("Serif", Font.BOLD, 25));

    add(changeBut, "Center"); 
       
    setTitle("Button Methods");
    setSize(300, 300);
    setVisible(true);
  }
  public void actionPerformed(ActionEvent e)
  {
    String str = e.getActionCommand();
    if(str.equals("Bharath"))
       changeBut.setLabel("India");
    else if(str.equals("India"))
       changeBut.setLabel("Bharath");

    String str1 = changeBut.getLabel();
    System.out.println("Now you clicked: " + str1);
  }
  public static void main(String args[])
  {
    new ButtonLabel();
  }
}


Event handling, for the above program, step-by-step is available in "AWT Button – Learning GUI – 8 Steps".

String str = e.getActionCommand();

The getActionCommand() method of ActionEvent class returns the label of the button user clicked. The string str contains either Bharath or India.

changeBut.setLabel(“India”);

The button label or button text can be changed with setLabel() method. Now the button label is changed to India from Bharath.

String str1 = changeBut.getLabel();

The getLabel() method of Button class returns the label of the button as a string and is displayed at the DOS prompt. Infact, you can display it on the frame itself using repaint() and drawString() method. The internals of event generation, sources and events are discussed elaborately in Event Handling.

2 thoughts on “Java Changing Button Label”

Leave a Comment

Your email address will not be published.