如何使用 Java 中的 JLabel 实现移动文本?

javaobject oriented programmingprogramming更新于 2024/5/10 15:44:00

JLabelJComponent 类的子类,JLabel 的对象在 GUI 上提供 文本说明信息。JLabel 可以显示一行 只读文本图像文本图像。JLabel 可以显式生成 PropertyChangeListener 接口。我们还可以使用 Timer  类在 JLabel 中实现移动文本 ,它可以设置一个计时器,使用速度(以毫秒为单位)this 作为参数。

示例

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();
   }
}

输出


相关文章