How can I extend the java.awt.Color class?
I am writing a graphics library in Java. It will be a front-end for several of the existing Java graphics packages, combining features from java.awt and javax.swing. I'm a teacher and I'm creating this library for my beginning students so they don't have to muck around with a hodge-podge of import statements. I'd also like to provide some additional built-in colors, to augment the limited set that java.awt.Color comes with
I wish to create a Color class that simply extends java.awt.Color. That way, the student doesn't have to import java.awt.Color directly. I've tried this:
package graphics;
public class Color extends java.awt.Color
{
}
开发者_Python百科But compiling evokes the error cannot find symbol - constructor Color()
. Apparently the java.awt.Color class lacks a default constructor and this is causing my class to fail compilation.
Will I just have to bite the bullet and write my own Color class and include some methods to translate between java.awt.Colors and my Colors?
Yes, The java.awt.Color does not have a default constructor, so you have to create at least one constructor am make a call to the super constructor:
public class Color extends java.awt.Color{
public Color(int rgb) {
super(rgb);
}
}
I would have answered with this example:
public class Color extends java.awt.Color {
public final static Color AZURE = new Color(240,255,255);
public static Color colorOf(String color) {
try {
return (Color)Color.class.getDeclaredField(color).get(null);
} catch(Exception notAvailable) {
System.out.println("RGB color " + color + " is not a predefined " +
"static color.");
return null;
}
}
}
精彩评论