How can we implement a moving text using a JLabel in Java?


A JLabel is a subclass of JComponent class and an object of JLabel provides text instructions or information on a GUI. A JLabel can display a single line of read-only text, an image or both text and an image. A JLabel can explicitly generate a PropertyChangeListener interface. We can also implement a moving text in a JLabel by using a Timer class, it can set a timer with speed(in milliseconds) and this as an argument.

Example

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class MovingTextLabel extends JFrame implements ActionListener {
   private JLabel label;
   public MovingTextLabel() {
      setTitle("MovingTextLabel");
      label= new JLabel(" Welcome to Tutorials Point ");
      label.setFont(new Font("Arial", 0, 25));
      add(label, BorderLayout.CENTER);
      Timer t = new Timer(400, this); // set a timer
      t.start();
      setSize(400, 300);
      setVisible(true);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
   public void actionPerformed(ActionEvent e) {
      String oldText = label.getText();
      String newText= oldText.substring(1)+ oldText.substring(0,1);
      label.setText(newText);
   }
   public static void main (String[] args) {
      new MovingTextLabel();
   }
}

Output

Updated on: 10-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements