I am Java beginner and I am trying to code something. Currently I am stucked at getPixelColor(). It's the method of class Robot. I can get pixel color but don't know how to compare with other color. Let's say that my other color is stored in some int variable and I need to compare these two colors. But I can't compare these two colors, because it throws this error "incomparable types:int and java.awt.Color". So how convert it to int?
Thanks
Probably something like:
if(color.getRGB() == stored_color){
}
Anyways, you need to access the Color object's getRGB function to compare the numeric value to another int.
Try
Color otherColor = new Color(someInt);
and then
if (otherColor.equals(robot.getPixelColor(someX, someY))
{
...
}
Related
i just try to program pong with the use of java swing components.
My problem ist, that i need to store the coordinates of my JButton (my Paddle) in variables to be able to manipulate the position of the Button when moving.
I tried doing it that way:
int posP1_x= paddel1.getLocation().getX(); //Error
When compiling it says, that there is a lossy conversion from double to int. (But the retrun value of getX should be int and in the Point-Class the values are also stored as ints). When i try declaring posP1_x as double and print the variables value on the console, it always prints 0.0. But when i print paddel1.getLocation().getX() directly, it works...
double posP1_x= paddel1.getLocation().getX(); //Works
System.out.println(paddel1.getLocation().getX()); //Prints double value eg 110.0
System.out.println(posP1_x); //Prints double value with 0. --> 0.0
What could be the solution to save JButton Coordinates in Variables.
Thank you and have a nice day
Don't use getX(). Use .x. That's it. For example:
// either
int posP1_x= (int) paddel1.getLocation().getX();
// or
int posP1_x= paddel1.getLocation().x;
More importantly, look at the relevant API before posting here. If you'd simply look at the Point API, you'd have your answer.
I'm trying to write a change color method in Java that accepts an int parameter and changes that color based on that int. Valid colors will be in the range 1 - 6 for the six colors. You may decide which number (1-6) maps to which color. If the value is not in this range, make the circle red.
I am trying to do this without the use of an array list, but I am unsure how. Any ideas?
I've tried:
if(newColor == 1) {
newColor = "yellow";
}
And I get an error message saying 'incompatible types: java.lang.String cannot be converted to int.'
I've also tried:
if(newColor == 1) {
newColor.equals("yellow");
}
And I get an error message stating 'int cannot be dereferenced'.
1 is an int literal. If the compiler allows you to test newColor ==, then that means newColor must be an int variable. Being an int variable, it is only allowed to hold int values.
"yellow" is a String literal. The compiler will not allow you to assign a String value to an int variable. You may only assign String values to String variables.
You're going to need two variables: One to hold the given int value, and one to hold the String result.
Other languages (e.g., Ruby) might let you do it differently, but if you're going to use Java, then you are going to have to work within the Java rules to solve your problem.
An example of what I mean would be:
Color maroon = #800000;
Color red = #ff0000;
if (red <resembles> maroon) //which would return true because they're both red colors.{
//...
} else {
System.out.println("The colors did not resemble.");
}
Would this be possible and if so then how would I go about doing this?
Well I think the best way would be to simply compare the red components:
public boolean checkIfSimilar(Color c1, Color c2) {
int threshold = 10;
if(c1.getRed() - c2.getRed() < threshold){
return true;
}
return false;
}
You just define your threshold depending on how much you want those colors to be similar.
There is no easy way to do this without some degree of subjectivity: there is no single notion of "red". Even for the examples you give above (blood, apples, strawberries), one can give examples which are not red (e.g. lobster blood is blue, the Granny Smith varietal of apple is green, underripe strawberries are green), and even the appearance of "red" examples of these things is quite different depending upon lighting conditions.
You need to determine what you consider "red" to be in a way that is sufficient for your application. This will probably require the comparison of the components of the color to the components of an "ideal redness"; however, you could use a far more advanced technique such as using some machine learning model. Given the way in which you have asked the question, I assume you are looking for a rather basic solution.
You should consider using a different color space to RGB. For example, HSL (Hue Saturation Lightness) gives you something resembling a normalized color in its first component (the "hue"). You could compare this hue to some reference value of redness, and you get brightness-invariant comparison.
The two main caveats I would mention with HSL:
Hue is a circular space, i.e. you need to consider the wrapping of its value in determining the distance from a reference point;
Checking the saturation is important, since hue is undefined for a "color" such as white or black.
I want to define a grid in which I specify an (x,y) coordinate for each point in the grid. So I want to do something like this:
int [][] pt;
for (x=0; x<numX; x=x+1) {
for (y=0; y<numY; y=y+1) {
pt[x][y] = {xval, yval};
}
}
The reason why is because I am mapping the values of an orderly grid to a disorderly grid. The above code of course causes an exception (unexpected token "{").
What is the best way to do what I'm trying to do? Thanks.
Two things:
You havent initialized your array (maybe you did just didnt put in code)
You are trying to put two values into a place where only one can be held.
Initialize your array like this (if you didnt)
int[][] pt = new int[numX][numY];
To store both values in the array you will need to use an object. The java Point class would be an example of something you could use
Point[][] pt = new Point[numX][numY];
for (x=0; x<numX; x=x+1) {
for (y=0; y<numY; y=y+1) {
pt[x][y] = new Point(xval, yval);;
}
}
You basically want to store a fixed number of values inside every array cell?
Then you are limited with 2 major cases:
Use an object
Java doesn't have user defined value types, so you are forced to use full-blown objects on the heap (with little hope that JVM will be very clever and optimize it, but chances are near zero), be it an array, or any other class.
If both of your values are less than 64 bits, you can pack them in built-in primitive type (such as long) using bitwise arithmetic. (You must be very careful here)
ints are 32 bit, so you can pack 2 ints in 1 long.
pt[x][y] = {xval, yval} is illegal, pt[][] is a double dimensional array. It only can store one value. Just like this pt[x][y] = value
You may try java map.
In order to save Color attributes of a graphical object in my application, I saved the string representation of this Color in a data file.
For instance, for red I save: java.awt.Color[r=255,g=0,b=0].
How can I convert this string representation into a Color so that I can use it again after loading my data file ?
Thank you.
You may wish to use getRGB() instead of toString(). You can call
String colorS = Integer.toString(myColor.getRGB());
Then you can call
Color c = new Color(Integer.parseInt(colorS));
Using toString() "might vary between implementations." Instead save String.valueOf(color.getRGB()) for later reconstruction.
From the documentation of Color#toString
Returns a string representation of this Color. This method is intended to be used only for debugging purposes. The content and format of the returned string might vary between implementations. The returned string might be empty but cannot be null.
In other words, I wouldn't rely on being able to back-convert the string to the Color. If you insist on doing this, however, you can try to parse the numbers out of the string and hope that it will work with no guarantees.
Something like this seems to work for ME for NOW:
Scanner sc = new Scanner("java.awt.Color[r=1,g=2,b=3]");
sc.useDelimiter("\\D+");
Color color = new Color(sc.nextInt(), sc.nextInt(), sc.nextInt());
I don't recommend actually doing this, however.
I suggest you look into java's built-in serialisation technology instead. (I note that Color implements Serializable.)
Use the getRGB() method to get the int representation of the Color, then you save the int value and recreate the Color using that value. No parsing needed.
The easiest thing is to rethink the way you store the string representation. Get rid of all the labeling, and just store red as the string "0xFF0000". Then you can easily parse that string to get the single value for rgb, and send it to the Color constructor.
The alternative is to parse the more complicated string as you are now saving it "java.awt.Color[r=255,g=0,b=0]".
You can see the constructors for Color here:
http://java.sun.com/javase/6/docs/api/ (search "all classes" for Color).
Peter
Don't use the toString(). Use getRGB() / new Color(rgb) to save/restore the value of the color.
Stephan's answer helped me with this. However, I found that I needed to add a 'true' to the syntax in order to restore the color.
// convert to string
String colorS = Integer.toString(myColor.getRGB());
// restore colour from string
Color c = new Color(Integer.parseInt(colorS), true);