Home >Java >javaTutorial >How to Update a JLabel Every X Seconds with Data from an ArrayList in Java?
Update JLabel Every X Seconds from ArrayList in Java
In this article, we aim to address the challenge of dynamically updating a JLabel every X seconds based on words obtained from an ArrayList using a Swing Timer.
Problem
We have a Java program that reads words from a text file and displays them sequentially on the console with a 2-second delay between each word. The goal is to replicate this behavior in a Spring-based GUI with a JLabel that flashes the words with similar intervals.
Solution
Here's how the solution can be implemented in Java:
// Assuming you have an array list of strings named "words" final Timer timer = new Timer(500, null); ActionListener listener = new ActionListsner() { private Iterator<String> it = words.iterator(); @Override public void actionPerformed(ActionEvent e) { if (it.hasNext()) { label.setText(it.next()); } else { timer.stop(); } } }; timer.addActionListener(listener); timer.start();
By following these steps, you can create a dynamic JLabel that updates its text every X seconds based on the words from the ArrayList, allowing for a flashing word effect in your GUI.
The above is the detailed content of How to Update a JLabel Every X Seconds with Data from an ArrayList in Java?. For more information, please follow other related articles on the PHP Chinese website!