Java Changing Button Label

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


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 Reply

Your email address will not be published. Required fields are marked *