java android random colors - java

I want my code to automatically pick random colors... at the moment I have it static... I want it when it changes color, just randomly pick any color in the world of RGB...
the below is what I have, any kind of help I can get on this is greatly appreciated!
private float[][] BackgroundColors = { { 141, 189, 193 }, { 116, 84, 62 },
{ 73, 113, 116 }, { 193, 163, 141 }, { 15, 11, 6 }, };
private void getCurrentColor() {
CurrentColorNumber++;
if (CurrentColorNumber >= 5) {
CurrentColorNumber = 0;
}
CurrentColor = new Color(
BackgroundColors[CurrentColorNumber][0] / 255.0f,
BackgroundColors[CurrentColorNumber][1] / 255.0f,
BackgroundColors[CurrentColorNumber][2] / 255.0f, 1);
}

Suppose I have a text view and I want a random color for the text
on every button click.
Just check this code on your program.
I hope this logic helps you.
TextView Display = (TextView) findViewById(R.id.tvresult);
Random mRandom = new Random();
Display.setText("WHAT????");
Display.setTextSize(mRandom.nextInt(75));
Display.setTextColor(Color.rgb(mRandom.nextInt(265),
mRandom.nextInt(265), mRandom.nextInt(265)));

you could use Random to peek four numbers between 0 and 255, and then use Color.argb to return the correspondent color. E.g.
private Random mRandom = new Random();
private int randomColor() {
int r = mRandom.nextInt(256);
int g = mRandom.nextInt(256);
int a = mRandom.nextInt(256);
int b = mRandom.nextInt(256);
return Color.argb(a, r, g, b);
}
you don't need the alpha channel you can either set a = 255, or using
Color.rgb(r, g, b) instead of Color.argb. Thanks to #maraca that made me notice it

You can that with Random class:
Random r = new Random();
BackgroundColors[r.nextInt(BackgroundColors.length)];

Related

Change the picture when pressing the button

Tell me how to make it change to the next one when you click on a picture. I use a library "ControlP5, cp5.addbutton" with a regular button in which I could do without a picture.
I have two examples, with a regular button and a picture, where I use a different way to change the picture by hovering the mouse and clicking in order to show you clearly.
"minutesss1" - a regular button with public void minutesss1() which uses .setCaptionLabel("ВЫКЛ").
"minutesss2" - How I think to use for the picture .setCaptionLabel("ВЫКЛ") / Not required ?????
Complete example code:
import controlP5.*;
ControlP5 cp5;
int min=0;
Button minutess1;
Button minutess2;
void setup() {
size(700,400);
PFont fontn = createFont("Times New Roman",18);
cp5 = new ControlP5(this);
PFont p = createFont("Times New Roman",18);
ControlFont font=new
ControlFont(p);
cp5.setFont(font);
minutess1 = cp5.addButton("minutesss1")
.setCaptionLabel("ВЫКЛ")
.setPosition(200,200)
.setSize(99,25);
PImage[] imgs1 = {loadImage("0.png"),loadImage("1.png"),loadImage("2.png")}; // ,loadImage("3.png"),loadImage("4.png"),loadImage("5.png"),loadImage("6.png")
minutess2 = cp5.addButton("minutesss2")
//.setCaptionLabel("ВЫКЛ")
.setPosition(400,200)
.setImages(imgs1);
minutess2.setSize(99,25);
textFont(fontn);}
public void minutesss1() {
min+=10;
if (min>60) {min=0; minutess1.setCaptionLabel("ВЫКЛ"); }
else minutess1.setCaptionLabel(str(min)+" Мин");}
void draw(){
background(0);
fill(255);}
It's great that you've posted the code formatted like that.
It would be even better if you format it in Processing (Ctrl + T) before to make it easier to read.
It is difficult to fully understand what your asking.
If you're using a translation tool you can try breaking long phrases into smaller, simpler sentences. Hopefully the translation tool will do a better job.
From what I can understand there are two questions here:
How can you call the same minutes updating function that works for the first button from the second button ?
How can you use custom images to skin the second button ?
The first question can be tackled multiple ways.
Here are a couple of options:
Option 1: Use controlEvent which gets called automatically when updating any controlP5 component. You can check which button was pressed and call a function accordingly:
import controlP5.*;
ControlP5 cp5;
int min=0;
Button minutess1;
Button minutess2;
void setup() {
size(700, 400);
PFont fontn = createFont("Times New Roman", 18);
cp5 = new ControlP5(this);
PFont p = createFont("Times New Roman", 18);
ControlFont font=new
ControlFont(p);
cp5.setFont(font);
minutess1 = cp5.addButton("minutesss1")
.setCaptionLabel("ВЫКЛ")
.setPosition(200, 200)
.setSize(99, 25);
//PImage[] imgs1 = {loadImage("0.png"), loadImage("1.png"), loadImage("2.png")}; // ,loadImage("3.png"),loadImage("4.png"),loadImage("5.png"),loadImage("6.png")
PImage[] imgs1 = {getImage(99,25,color(0,0,192)),
getImage(99,25,color(0,0,240)),
getImage(99,25,color(0,0,120))};
minutess2 = cp5.addButton("minutesss2")
//.setCaptionLabel("ВЫКЛ")
.setPosition(400, 200)
.setImages(imgs1);
minutess2.setSize(99, 25);
textFont(fontn);
}
PImage getImage(int w, int h, int c){
PImage img = createImage(w, h, RGB);
java.util.Arrays.fill(img.pixels, c);
img.updatePixels();
return img;
}
public void minutesss1() {
min+=10;
if (min>60) {
min=0;
minutess1.setCaptionLabel("ВЫКЛ");
} else minutess1.setCaptionLabel(str(min)+" Мин");
println(min,minutess1.getCaptionLabel().getText());
}
void draw() {
background(0);
fill(255);
}
public void controlEvent(ControlEvent event) {
if(event.controller() == minutess2){
minutesss1();
}
}
Option 2: Extract the instructions of the first button press function into a separate function that can be called by both. This is probably simpler and more intuitive to read:
import controlP5.*;
ControlP5 cp5;
int min=0;
Button minutess1;
Button minutess2;
void setup() {
size(700, 400);
PFont fontn = createFont("Times New Roman", 18);
cp5 = new ControlP5(this);
PFont p = createFont("Times New Roman", 18);
ControlFont font=new
ControlFont(p);
cp5.setFont(font);
minutess1 = cp5.addButton("minutesss1")
.setCaptionLabel("ВЫКЛ")
.setPosition(200, 200)
.setSize(99, 25);
//PImage[] imgs1 = {loadImage("0.png"), loadImage("1.png"), loadImage("2.png")}; // ,loadImage("3.png"),loadImage("4.png"),loadImage("5.png"),loadImage("6.png")
// don't have images to reproduce: making new ones
PImage[] imgs1 = {getImage(99,25,color(0,0,192)),
getImage(99,25,color(0,0,240)),
getImage(99,25,color(0,0,120))};
minutess2 = cp5.addButton("minutesss2")
//.setCaptionLabel("ВЫКЛ")
.setPosition(400, 200)
.setImages(imgs1);
minutess2.setSize(99, 25);
textFont(fontn);
}
PImage getImage(int w, int h, int c){
PImage img = createImage(w, h, RGB);
java.util.Arrays.fill(img.pixels, c);
img.updatePixels();
return img;
}
void updateMinutes(){
min+=10;
if (min>60) {
min=0;
minutess1.setCaptionLabel("ВЫКЛ");
} else minutess1.setCaptionLabel(str(min)+" Мин");
println(min,minutess1.getCaptionLabel().getText());
}
public void minutesss1() {
updateMinutes();
}
public void minutesss2() {
updateMinutes();
}
void draw() {
background(0);
fill(255);
}
Regarding the second part of your question it's unclear if you want to have images just for the default controlP5 states(default, over, active, highlight) using setImages() or not. If you pass more than 4 or less than 3 images they will be ignored as you can see in the source code
If you want to display a different image for each minutes update (e.g. off, 10 , 20, 30, 40, 50, 60) then you will need to make your own custom button.
The logic isn't that complicated and you can use the Button Example as a simpler starting point.
It would be great to encapsulate that more complex custom functionality and you'd need a few Object Oriented Programming (OOP) basics for that. You can check out the Objects tutorial and example
For illustration purposes here's a separate sketch that would display a different image for each of the button press states (ignoring the over/highlight states):
ImageButton button;
void setup(){
size(300, 300);
// button dimensions
int w = 75;
int h = 25;
// test with generated images
button = new ImageButton(112, 137, w, h,
new PImage[]{
// use loadImage with your own images instead of getImage :)
getImage(w, h, color(192, 0, 32 * 2)), // off
getImage(w, h, color(0, 0, 32 * 3)), // 10
getImage(w, h, color(0, 0, 32 * 4)), // 20
getImage(w, h, color(0, 0, 32 * 5)), // 30
getImage(w, h, color(0, 0, 32 * 6)), // 40
getImage(w, h, color(0, 0, 32 * 7)), // 50
getImage(w, h, color(0, 0, 32 * 8)), // 60
});
// loading images will be something similar to:
//button = new ImageButton(112, 137, w, h,
// new PImage[]{
// loadImage("0.png"), // off
// loadImage("1.png"), // 10
// loadImage("2.png"), // 20
// loadImage("3.png"), // 30
// loadImage("4.png"), // 40
// loadImage("5.png"), // 50
// loadImage("6.png"), // 60
// });
}
void draw(){
background(0);
button.draw();
}
void mousePressed(){
button.mousePressed(mouseX,mouseY);
println(button.min);
}
// test images to represent loaded state images
PImage getImage(int w, int h, int c){
PImage img = createImage(w, h, RGB);
java.util.Arrays.fill(img.pixels, c);
img.updatePixels();
return img;
}
// make a custom image button class
class ImageButton{
// minutes is the data it stores
int min = 0;
// images for each state
PImage[] stateImages;
// which image to display
int stateIndex;
// position
int x, y;
// dimensions: width , height
int w, h;
// text to display
String label = "ВЫКЛ";
ImageButton(int x, int y, int w, int h, PImage[] stateImages){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.stateImages = stateImages;
}
void mousePressed(int mx, int my){
// check the cursor is within the button bounds
boolean isOver = ((mx >= x && mx <= x + w) && // check horizontal
(my >= y && my <= y + h) ); // check vertical
if(isOver){
min += 10;
stateIndex++;
if (min>60) {
min = 0;
stateIndex = 0;
label = "ВЫКЛ";
} else {
label = min + " Мин";
}
}
}
void draw(){
// if the images and index are valid
if(stateImages != null && stateIndex < stateImages.length){
image(stateImages[stateIndex], x, y, w, h);
}else{
println("error displaying button state image");
println("stateImages: ");
printArray(stateImages);
println("stateIndex: " + stateIndex);
}
// display text
text(label, x + 5, y + h - 8);
}
}

How to call 2 different paint methods in the same program?

I'm trying to make a simple guess the number game and when the user guesses a number between a specific range from the actual answer it will draw a rectangle with a different colour. As of now i'm just testing and have created 2 paint methods and want to now how to call the method "paint2".
import java.awt.*;
import hsa.Console;
import javax.swing.JFrame;
import java.util.Random;
import java.awt.Canvas;
import java.awt.Graphics;
public class MashGuessTheNumber extends Canvas {
static Console c; // The output console
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("My Drawing");
Canvas canvas = new MashGuessTheNumber();
canvas.setSize(400, 400);
frame.getContentPane().add(canvas);
frame.pack();
frame.setVisible(true);
MashGuessTheNumber sm = new MashGuessTheNumber();
c = new Console();
int loop = 0;
while (loop == 0) { // loop used to continue looping the questions after one is answered
int answer = 0;
c.println("Welcome to the guess the number game!");
c.println("What is your name?");
String name = c.readLine();
c.print("why, hello there ");
c.println(name);
c.println("What diffuculty would you like to play?(easy/medium/hard)");
String diff = c.readLine();
if (diff.equalsIgnoreCase("easy")) {
// *Location of random number generator*
c.println("So you chose easy, huh");
c.println("I'm thinking of a number between 1 and 10");
int guess = 1;
answer = (int) (Math.random() * ((10 - 1) + 1));
while (guess != answer) {
c.println("What is it?");
guess = c.readInt();
c.println(answer);
if ((((guess - answer) < 3) && ((guess - answer) > 0))
|| (((answer - guess) < 3) && ((answer - guess) > 0))) {
c.println("EXTREMELY HOT");
}
}
if (guess == answer) {
c.println("You did it!");
}
}
if (diff.equalsIgnoreCase("medium")) {
// *Location of random number generator*
c.println("So you chose medium, huh");
c.println("I'm thinking of a number between 1 and 100");
c.println("What is it?");
String guess = c.readLine();
answer = (int) (Math.random() * ((100 - 1) + 1));
}
if (diff.equalsIgnoreCase("hard")) {
// *Location of random number generator*
c.println("So you chose hard, huh");
c.println("I'm thinking of a number between 1 and 1000");
c.println("What is it?");
String guess = c.readLine();
answer = (int) (Math.random() * ((1000 - 1) + 1));
}
c.println("Would you like to play again?(y/n)"); // if answerd with "y" the loop will repeat
String cont = c.readLine();
if (cont.equalsIgnoreCase("y")) {
loop = 0;
} else {
for(int i=1;i<=24;i++){
c.println(" ");
c.setCursor(12, 30);
c.println("See you next time. Bye!");
loop = 1; // Stops the loop and says bye to the user
}
}
// Place your program here. 'c' is the output console
}
public void paint(Graphics g) {
int x[] = { 35, 75, 75, 35 };
int y[] = { 10, 10, 200, 200 };
g.setColor(Color.black);
int numberofpoints = 4;
g.drawPolygon(x, y, numberofpoints);
}
public void paint2(Graphics g) {
int x[] = { 35, 75, 75, 35 };
int y[] = { 10, 10, 200, 200 };
g.setColor(Color.blue);
int numberofpoints = 4;
g.drawPolygon(x, y, numberofpoints);
}
// main method
} // MashGuessTheNumber class
I'm just trying to draw a different rectangle as of now over top the first one whenever I want and if there is another way that doesn't use two methods that would also be helpful
I'm not seeing where you call paint() at all, but I would make a second parameter that would act as a flag telling me whether to draw a blue or black rectangle. This would get rid of repeated code.
public void paint (Graphics g, Color color)
{
int x[] = {35, 75, 75, 35};
int y[] = {10, 10, 200, 200};
g.setColor (color);
int numberofpoints = 4;
g.drawPolygon (x, y, numberofpoints);
}
I don't know if 'Color' is the correct object to use to pass in a color, but the point is to pass in something that will help you choose what color to make the rectangle so that way you don't have to write two very similar methods. You will call paint() like this:
if(some condition) {
paint(g, Color.blue);
}
else {
paint(g, Color.black);
}
In the Java Swing framework, you don't call Canvas.paint() yourself. But, you can use your own intance variables.
If you add an instance variable to your MashGuessNumber class
private Color myColor = Color.BLACK;
Then modify your if statement
if (count == answer) {
System.out.println("You did it1);
myColor == Color.BLUE;
repaint(); // already a Canvas method
}
Then modify your paint() method
public void paint (Graphics g, Color color)
{
int x[] = {35, 75, 75, 35};
int y[] = {10, 10, 200, 200};
g.setColor (myColor);
int numberofpoints = 4;
g.drawPolygon (x, y, numberofpoints);
}
This should do the trick.
The call to repaint() tells Swing to redraw the canvas by calling your paint() method. Otherwise the system would have no way of knowing that your Canvas needs to be redrawn.

Multicolored changing text in java

Id like multicolored changing text, I made a list with all the colors
I have 5 g.drawString(); functions running, each of them should be the next color in the list (one above each other.)
private Color[] colors = new Color[12];
Then in my constructor:
colors[0] = new Color(255, 0, 0);
colors[1] = new Color(255, 127, 0);
colors[2] = new Color(255, 255, 0);
colors[3] = new Color(127, 255, 0);
colors[4] = new Color(0, 255, 0);
colors[5] = new Color(0, 255, 127);
colors[6] = new Color(0, 255, 255);
colors[7] = new Color(0, 127, 255);
colors[8] = new Color(0, 0, 255);
colors[9] = new Color(127, 0, 255);
colors[10] = new Color(255, 0, 255);
colors[11] = new Color(255, 0, 127);
How would I make each each letter a different color?
Set The Color: g.setColor(Color object);
Example: g.setColor(colors[5]);
Write Text: g.drawString(String, x, y);
Example: g.drawString("S", 200, 300);
So, Id like S to be the color, colors[0], I made a table below:
Starting | First | Second | Fifth
S -- 0 11 10 7
N -- 1 0 11 8
A -- 2 1 0 9
K -- 3 2 1 10
E -- 4 3 2 11
So it would loop around though each color:
I tried making a function for this, I deleted the code because I'm an idiot -_-
In my main class, I have a game loop that calls the tick and render methods, tick first then render.
I have an enum called STATE which contains menu and game, then the variable gameState of the type state is set to STATE.menu
public enum state {
Menu,
Game,
}
public state gameState = state.Menu;
When gameState is equal to STATE.menu it will call menu.render(g ( <-- The variable im using for Graphics));
Each class has its own render and tick method.
-Tick method, for setting variables etc, if statements, yada yada yada
-Render method, anything to do with drawing pixels
Because the tick method is called every 0.0000000000000000001 seconds, the color changes every 9 millionth of a second and it looks very derpy.
So ill need a timer of some sorts that I can configure with a variable
I want each of the letters to be a different color, one after another in the list
you can refer to the table above if you don't understand but as an example,
the letter a should be colors[0]
and then b, colors[1]
and c, colors[2]
the colors should alter,
so a would be colors[2]
so b would be colors[0]
so c would be colors[1]
I've probably been unclear on 1001 things, so please shout at me in the comments ^-^
Thanks for reading!
If I understood correctly, there are mainly two issues:
Painting the letters in different colors, cycling through the given array
Updating the colors (but at a fixed time, not with every "tick")
Cycling through the colors can be achieved by introducing a "colorOffset". You can add this color offset to the index that you use to access the color in the array, and take this modulo the array length to obtain a valid array index:
int colorOffset = ... // Counted up or down all the time
// The index of the color for the i'th letter
int colorIndex = (i+colorOffset)%colors.length;
if (colorIndex < 0) colorIndex += colors.length;
g.setColor(colors[colorIndex]);
The second part, regarding the update: I assume that you have a game loop that is run in an own thread. Then, in thisTickMethodThatYouHaveBeenTalkingAbout, you can check the current system time with System.nanoTime(), and compute the time that has passed since the last update. If the time is larger than the desired interval, you perform an update, by increasing the colorOffset and triggering a repaint() (if necessary - you might cover this already with your render() method).
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MulticolorTextAnimation
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MulticolorTextAnimationPanel m = new MulticolorTextAnimationPanel();
f.getContentPane().add(m);
Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
while (true)
{
m.thisTickMethodThatYouHaveBeenTalkingAbout();
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
return;
}
}
}
});
thread.setDaemon(true);
thread.start();
f.setSize(500,200);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class MulticolorTextAnimationPanel extends JPanel
{
private String string;
private Color colors[];
private int colorOffset = 0;
private long lastUpdateNs = -1;
private final long updateIntervalMs = 250;
public MulticolorTextAnimationPanel()
{
setFont(new Font("Dialog", Font.BOLD, 45));
string = "I am a string!";
colors = new Color[12];
colors[0] = new Color(255, 0, 0);
colors[1] = new Color(255, 127, 0);
colors[2] = new Color(255, 255, 0);
colors[3] = new Color(127, 255, 0);
colors[4] = new Color(0, 255, 0);
colors[5] = new Color(0, 255, 127);
colors[6] = new Color(0, 255, 255);
colors[7] = new Color(0, 127, 255);
colors[8] = new Color(0, 0, 255);
colors[9] = new Color(127, 0, 255);
colors[10] = new Color(255, 0, 255);
colors[11] = new Color(255, 0, 127);
}
public void thisTickMethodThatYouHaveBeenTalkingAbout()
{
long ns = System.nanoTime();
if (lastUpdateNs < 0)
{
lastUpdateNs = ns;
}
long passedNs = (ns - lastUpdateNs);
long passedMs = passedNs / 1000000;
if (passedMs > updateIntervalMs)
{
// Increase or decrease the color offset,
// depending on whether the colors should
// cycle forward or backward
colorOffset--;
repaint();
lastUpdateNs = ns;
}
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
FontMetrics fontMetrics = g.getFontMetrics();
int x = 100;
int y = 100;
for (int i=0; i<string.length(); i++)
{
char c = string.charAt(i);
int colorIndex = (i+colorOffset)%colors.length;
if (colorIndex < 0)
{
colorIndex += colors.length;
}
g.setColor(colors[colorIndex]);
g.drawString(String.valueOf(c), x, y);
x += fontMetrics.charWidth(c);
}
}
}

Processing mapping always out of bounds

I'm trying to make a graph in processing, but keep getting the "ArrayIndexOutOfBounds" error. I am having a hard time understanding the concept of the map() syntax, could anyone clear it up for me? I'm not sure what every number is supposed to stand for within map(x,y,z,a,b);
String[] name = {
"1st:",
"5th:",
"10th:",
"15th:",
"20th:",
"25th:",
"30th:"
};
int[] temperature = {
81,
82,
84,
85,
87,
88,
90
};
void setup(){
size(200,200);
}
void draw(){
int x=0;
for(int i=0;i<10;i++){
if(mouseX>x && mouseX<=x+40){
fill(255,40,40);
}else{
fill(50);
}
float h = map(temperature[i], 0, 100, 0, 200);
rect(x+4,height-h,32,h);
x+=40;
}
}
Your arrays have 7 elements, but you iterate 10 times.
for(int i=0;i<10;i++){
...
float h = map(temperature[i], 0, 100, 0, 200);
}
Either you fill up your arrays with additional 3 elements, or better: Instead of the number 10 you should use i < temperature.length() as condition in for-loop.

Frequency distribution of an array

Hi I am trying to get the frequency of an array for text font sizes and colors, when I have string of words and I count the frequency I want to change the size of the word and color according to their overall value in size, I have tried to divide the frequency/average *10 but gives me null, but on my calculator it gives me ie, 80/100 *10 = 8, this would the take an index of 8 and have 180 font size
can anyone help me with this?
private static int[] fontWeight = { 40, 60, 80, 100, 120, 140, 160,180 };
private static Color[] Colors = { Color.blue, Color.cyan, Color.yellow, Color.green, Color.red,
Color.orange, Color.pink,Color.pink };
//main
for (String str: wordList) {
int wordFreq = randWord.getFrequency();//assume 80 comes here
int fontSize = getFontSize(wordFreq);
Font font = new Font(Font.SANS_SERIF, Font.ITALIC, fontWeight [fontSize ]);
graphics.setFont(font);
graphics.setColor(Colors[fontSize]);
FontMetrics fm = graphics.getFontMetrics();
graphics.drawString(randWord.getWord() + "", x, y);
}
//method
private static int getFontSize(int freq) {
int newFont = (int) (freq/100)*10;
if (newFont >= 5) newFont = 6;
// if(newFont<2)
// newFont = 1;
System.out.println("freq " + freq + " font index" + newFont + " font size "
+ fontWeight[newFont]);
return newFont;
}
Thanks for your help
Integer division behaves differently, if numerator is smaller than denominator the result is 0. for example 80/100 returns 0. what you would do is multiply numerator with that 10 and then divide it.
int newFont = (int) (freq/100)*10;
should change to
int newFont = (int) (freq*10 / 100);

Categories