JLabel เป็น subclass ของ JComponent และออบเจ็กต์ JLabel ให้ text instructions หรือ information บน GUI JLabel แสดงข้อความอ่านอย่างเดียวได้ single line, image หรือทั้ง text และ image JLabel สามารถ generate PropertyChangeListener interface ได้ เราสามารถ implement moving text ใน JLabel โดยใช้คลาส Timer ซึ่งตั้งค่า timer ด้วย speed (ใน milliseconds) และ this เป็น argument
ตัวอย่าง
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); // ตั้งค่า 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
