Change JLabel Text After Creation in Java



In this article, we will learn to change JLabel text after creation in Java. We'll cover two scenarios: changing the label text immediately after creation and updating it in response to a button click.

Different approaches to change JLabel text after creation

Below are the different approaches to change JLabel text after the creation ?

Update JLabel text using setText() method

Following are the steps to update JLabel text immediately after creation ?

  • First we will import JFrame, JLabel, and Font from javax.swing and java.awt.
  • Create JFrame and JLabel by instantiating a JFrame and a JLabel, and set the label's initial text.
  • Change the label text by using setText() on the label to update its text.
  • Add the label to the frame, set the frame's size and layout, and make it visible.

Example

Below is the Java program to change JLabel text after creation ?

import java.awt.Font;
import javax.swing.*;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Label Example");
      JLabel label;
      label = new JLabel("First Label");
      label.setBounds(50, 50, 100, 30);
      label.setFont(new Font("Verdana", Font.PLAIN, 13));
      // changing text
      label.setText("Updated text");
      frame.add(label);
      frame.setSize(500,300);
      frame.setLayout(null);
      frame.setVisible(true);
   }
}

Output

Update JLabel text using a button click

Following are the steps to change JLabel text after creation using a button click ?

  • Import JFrame, JLabel, JButton from javax.swing and ActionEvent, ActionListener from java.awt.event
  • Instantiate a JFrame, a JLabel with initial text, and a JButton.
  • Attach an ActionListener to the button to change the label's text when clicked.
  • Add both the label and button to the frame, set the frame's size and layout, and make it visible.

Example

import java.awt.Font;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Label Example");
      JLabel label = new JLabel("First Label");
      label.setBounds(50, 50, 200, 30);
      label.setFont(new Font("Verdana", Font.PLAIN, 13));
      
      JButton button = new JButton("Change Text");
      button.setBounds(50, 100, 150, 30);
      
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            label.setText("Text changed on button click");
         }
      });
      frame.add(label);
      frame.add(button);
      frame.setSize(500, 300);
      frame.setLayout(null);
      frame.setVisible(true);
   }
}

Output

Updated on: 2024-09-16T23:24:47+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements