I'm programming a game in Java slick and I want to add a message management. There should be a ArrayList which contains all not yet sent messages. Every 2 seconds the next item in the list should be displayed.
My logic:
In the update methode the first message should be displayed. After 2 seconds this item gets removed.
My problem is that just the first one is displayed and the others not. When I was debugging I noticed that after these 2 seconds the timer continues to remove the first item without a 2 second break.
Please can you help me to find the problem or a better logic.
Here is some of my coding.
Mothode to put a message into the queue
public static void showMessage(String message){
msgHandler.addMessage(message);
}
Render methode
public void render(GameContainer gameContainer, Graphics g) throws SlickException {
msgHandler.getCurrentMessage().displayMessage(g);
if(msgHandler.isTimerCompleted()){
msgHandler.next();
}
}
Message manager class
public class MessageHandler {
private ArrayList<Message> messages;
private int duration = 2000;
private Timer timer = new Timer();
private boolean isTimerCompleted = true;
public MessageHandler() {
messages = new ArrayList<>();
}
public void next() {
isTimerCompleted = false;
timer.schedule(new TimerTask() {
@Override
public void run() {
if (messages.size() > 0) {
messages.remove(0);
}
System.out.println("test");
}
}, duration);
isTimerCompleted = true;
}
public Message getCurrentMessage() {
if (messages.size() > 0)
return messages.get(0);
return new Message("");
}
public void addMessage(String message, int x, int y) {
messages.add(new Message(message, x, y));
}
public void addMessage(String message) {
messages.add(new Message(message));
}
}