简体   繁体   中英

How can I change the colour of my window background randomly in java?

I am working on this program just for fun and had this idea of implemented a random background colour changer. Doing research and through my knowledge I have managed to come across a 1 line code which does that as I require. But I am having trouble understand the full code. Could someone explain it to me please, I will really appreciate it... The code is below.

new Color((int) (Math.random() * 0x1000000))

What I believe this code is doing is that creates a new instance of the method colour already created by java, converts that into an integer and gets a random number from that and times that by 0x1000000. Is this correct, please correct me.

I am finding it difficult to understand why does it times by 0x10000000, would that end up back to 0. Thanks, I really appreciate your help. thanks.

This code seems really dull to me. Because Math.random() returns a decimal number, multiplying it by 0x1000000 will multiply it by whatever 1,000,000 is in hexadecimal format.

The code I would use is:

Color c = new Color(new Random().nextInt(256), new Random().nextInt(256), new Random().nextInt(256));

or

Color c = new Color(Math.random(), Math.random(), Math.random());

The former would generate random integers up to 255 (inclusive) and put them as R, G and B parameters for a Color constructor, whereas, the latter would generate random decimals (sort of like percentages) as percentages for the R, G and B parameters for a Color constructor.

Test it out and report what you find! :)

Jarod.

Math.random() returns a double between 0.0 and 1.0, exclusive on the 1.0 side. Multiplying times 0x1000000 yields an int value between 0 and 0xffffff. Which fits a random color.

IMO using Random.nextInt(0xffffff) would be clearer. (Underneath it is doing the same thing)

0x1000000 is not an arithmetic expression, it's hexadecimal value for 16777216.

Math.random returns a random value between 0 and 1, which you then can multiply with the range you're looking for; in your case a full integer.

That integer is then used as argument to a Color-instance which will extract 3 bytes; red, green, and blue m, creating a very random color. As requested.

Alternatively, you could create each color-component individually, making more sense, perhaps, using something like;

color = new Color(
    Math.random() * 255, //red
    Math.random() * 255,  //green
    Math.random() * 255); //blue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM