Repainting a Screen

Published — Edited

This guide assumes that you have already read Resetting a Screen.

Executor Service

In order to show the results of the repaint method, ExecutorServices are used to update and repaint it every 16 milliseconds. The following example shows the creation of an ExecutorService which will print the time elapsed between each consecutive run.


public class ExampleA {
	public static void main(final String[] args) {
		final var previousTime = new AtomicLong(System.nanoTime());

		Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
			final var currentTime = System.nanoTime();
			final var elapsedTime = currentTime - previousTime.get();
			previousTime.set(currentTime);

			System.out.println("Time Elapsed (ms): " + TimeUnit.NANOSECONDS.toMillis(elapsedTime));
		}, 0, 16, TimeUnit.MILLISECONDS);
	}
}

Repainting

The following example updates the code point and colors color of every tile every 16 milliseconds. After the tiles have been updated, the VPanel is repainted to display the updates. As this example updates every tile, we do not need to use any of the reset methods before running the updates.


public class ExampleB {
	public static void main(final String[] args) {
		try {
			UIManager.setLookAndFeel(VTerminalLookAndFeel.getInstance(24));
		} catch (final UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}

		SwingUtilities.invokeLater(() -> {
			final var frame = new VFrame(40, 20);
			frame.setVisible(true);
			frame.pack();
			frame.setLocationRelativeTo(null);

			Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
				final var panel = frame.getContentPane();

				for (int y = 0 ; y < panel.getHeightInTiles() ; y++) {
					for (int x = 0 ; x < panel.getWidthInTiles() ; x++) {
						panel.setCodePointAt(x, y, getRandomCodePoint());
						panel.setBackgroundAt(x, y, getRandomColor());
						panel.setForegroundAt(x, y, getRandomColor());
					}
				}

				try {
					SwingUtilities.invokeAndWait(panel::repaint);
				} catch (final InterruptedException | InvocationTargetException e) {
					e.printStackTrace();
				}
			}, 0, 16, TimeUnit.MILLISECONDS);
		});
	}

	private static int getRandomCodePoint() {
		return ThreadLocalRandom.current().nextInt(33, 127);
	}

	private static Color getRandomColor() {
		switch (ThreadLocalRandom.current().nextInt(0, 6)) {
			case 0 -> { return Color.MAGENTA; }
			case 1 -> { return Color.GREEN; }
			case 2 -> { return Color.YELLOW; }
			case 3 -> { return Color.BLUE; }
			case 4 -> { return Color.RED; }
			case 5 -> { return Color.ORANGE; }
			default -> { return Color.WHITE; }
		}
	}
}

Further Reading