Label in java AWT example: A label is used to displays a string on something like buttons, field names and many more. This text can be changed easily by using design environment of an application. But we can’t change it from the time execution.This simple java AWT tutorial program deals with the changing given text from the buttons. An example source code is given below.
Change label in java AWT code:
Q: Write a Java code to changing the text of a label using AWT class.
[Useful: C Programming Guide] & [IT Companies List]
//Import statements import java.awt.*; import java.awt.event.*; //Class definition class ChangeLabelDemo extends Frame implements ActionListener { //Variable declaration Label la1; Button bu1,bu2; Panel pa1; public ChangeLabelDemo(String title) { super(title); pa1=new Panel(); la1=new Label("Welcome to Students3k!",Label.CENTER); bu1=new Button("Change Label");//Object creation bu2=new Button("Exit"); bu1.addActionListener(this); bu2.addActionListener(this); pa1.add(bu1); pa1.add(bu2); add("North",l1); //add(l1,BorderLayout.NORTH); add("South",pa1); } // © http://students3k.com – Karthikh Venkat public static void main(String args[]) { ChangeLabelDemo c=new ChangeLabelDemo("Change Label"); c.setSize(200,200); c.show(); //c.setVisible(true); } public void actionPerformed(ActionEvent e) { //Decision making statement if(e.getActionCommand().equals("Change Label")) { la1.setText("Welcome to J2EE!"); ba1.setLabel("Undo"); } else if(e.getActionCommand().equals("Undo")) { la1.setText("Welcome to Students3k!"); ba1.setLabel("Change Label"); } else if(e.getSource()==ba2) System.exit(0); } }