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

JavaObject Oriented ProgrammingProgramming

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

raja
Published on 01-Aug-2019 12:13:13
Advertisements