I'm developing a Java GUI application with the Swing framework where I need to show some text in a JTextArea that simulates an LCD display.
Each character of the text is appended every 250 ms through a Swing Timer but, If I don't hover with the mouse on the JTextArea, the update is not constant.
This is when I hover
This is when I don't hover
Here's an example, with a Timer based on this answer
public class App {
public static class LCDisplay extends JTextArea {
public LCDisplay() {
super(1, 20);
setEditable(false);
Font font = new Font(Font.MONOSPACED, Font.PLAIN, 50);
setFont(font);
setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
setForeground(Color.GREEN);
setBackground(Color.BLUE);
}
}
public static void main(String[] args) {
LCDisplay display = new LCDisplay();
display.setText(" ");
display.setBorder(BorderFactory.createLineBorder(Color.BLACK, 10, false));
Function<String, Boolean> setLCDisplayText = text -> {
int displayTextLength = display.getText().length();
try {
display.setText(display.getText(1, displayTextLength - 1));
} catch (BadLocationException e) {
e.printStackTrace();
}
display.append(text);
return display.getText().trim().isEmpty();
};
StringBuilder sb = new StringBuilder("Colore rosso");
for(int i=0; i<20; i++) {sb.append(' ');}
int interval = 250;
AtomicInteger supIndex = new AtomicInteger(0);
AtomicLong expected = new AtomicLong(Instant.now().toEpochMilli() + interval);
Timer slideText = new Timer(0, e -> {
int drift = (int) (Instant.now().toEpochMilli() - expected.get());
boolean exceeded = setLCDisplayText.apply(sb.charAt(supIndex.getAndIncrement()) + "");
if (exceeded) {
supIndex.set(0);
}
Timer thisTimer = (Timer) e.getSource();
expected.addAndGet(interval);
thisTimer.setInitialDelay(Math.max(0, interval - drift));
thisTimer.restart();
});
JFrame frame = new JFrame("app");
frame.add(display);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
slideText.start();
}
}
Maybe I'm doing something wrong but I really don't know how to solve.
Thanks in advance.