I am trying to create a jLabel that switches text messages via Timer. Currently, I have tried using for loops in the action listener but to no success.
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import java.awt.Rectangle;
public class TimerX extends JPanel{
private static final long serialVersionUID = 1L;
private JLabel jLabelNumber = null;
private Timer timer = new Timer(100, null);
private String [] messages = new String [4];{
messages [0] = "HI";
messages [1] = "How";
messages [2] = "Are";
messages [3] = "You";
}
public TimerX() {
super();
initialize();
}
private void initialize() {
jLabelNumber = new JLabel();
jLabelNumber.setBounds(new Rectangle(99, 85, 38, 16));
this.setSize(300, 200);
this.setLayout(null);
this.add(jLabelNumber, null);
ActionListener updater = new ActionListener(){
public void actionPerformed(ActionEvent event) {
for(int i = 0; i<messages.length;i++)
jLabelNumber.setText(messages[i]);
}
};
timer.addActionListener(updater);
timer.start();
}
}
The code only displays the the last String in the array. Help T.T
Every time your updater ActionListener runs, it loops through all of the messages, setting your label text to each message. At the end of your updater, the last message is showing in the label. It happens so fast, you just don’t see the first three messages being set, before they are overwritten.
You need an ActionListener that can remember what message it should display next.