Skip to content

Tag: java

Create a Scrolling Background in Java

Creating the next great side scroller? Well, you’ll need a scrolling background. And if you’re programming in Java, here’s an easy way to do it.

Quick Demo

Here’s a little demo of what we’re going to create. What’s happening is that there are two copies of the same image scrolling from the right to left. As one copy gets all the way off the left edge it leapfrogs back over to the right side. Normally they’d be the same, but it makes more sense on the demo for the two copies to be different colors.

The black box is the screen. Everything to the right or left of the box is happening off screen.

Click to start and click to stop.

How to create a random color in Java

Want to create a random color in Java? With a bit of math, plus Math.random(), it’s pretty easy.

A bit about colors

Colors on the computer are made up of a red, green, blue triplet; typically called RGB. And each of the 3 pieces can be in the range from 0 to 255. Java also allows us to create a color using floats for the values in the range of 0.0 to 1.0, or from 0% to 100% of that color. We’re going to use the floats.

As an example, pure red will have an R value of 1.0, a G value of 0.0, and a B value of 0.0.

So we know what numbers we need, but we want ’em random.