Changing the Label of a JButton Component in Java

JButton is a Swing Component which defined in package javax.swing.*;This program helps to change the Label(Caption) of the Button.The label of the Button “New” is changed into “Save” .

 

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class ChangeButtonLabel

{

JButton buttonn;

public static void main(String[] args)

{

ChangeButtonLabel cbl = new ChangeButtonLabel();

}

public ChangeButtonLabel()

{

JFrame frame = new JFrame("Change JButton Labell");

buttonn = new JButton("New");

buttonn.addActionListener(new MyButtonActionn());

frame.add(buttonn);

frame.setSize(400, 400);

frame.setVisible(true);

}

public class MyButtonActionn implements ActionListener

{

//define action for button

public void actionPerformed(ActionEvent actionevt)

{

String textt = (String)actionevt.getActionCommand();

if (textt.equals("New"))

{

buttonn.setText("Save");

final char belll='\u0007';//for ring

System.out.println(belll);

buttonn.setToolTipText("Save Caption");//for tooltip

buttonn.setBackground(Color.gray);

}

else

{

buttonn.setText("New");

buttonn.setBackground(Color.blue);

}

}

}

}

change label of a a button

Explanation …

In above example when the actionEvent “save” occurs, print(ring)the bell(belll).When we click on Button “New” then the caption of the button will change into “save” and the color of the button will change into gray. Again when we click on “Save” the caption of the button will again change into”New” and the color change into blue.

About Us

Rekha SetiaRekha Setia is a passionate blogger of Extra Computer Notes. if you have any ideas or any request me @