如何将颜色变量传递给下面的类?我想以 RGB (-155) 格式传递给代码变量:
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import javax.swing.Icon;
public class ColorIcon implements Icon {
ColorIcon(String iconColor) {
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(Color.decode(iconColor)); //<-- This is the problem
g.drawRect(7, 5, 11, 11);
g.fillRect(7, 5, 11, 11);
}
@Override
public int getIconWidth() {
return 16;
}
@Override
public int getIconHeight() {
return 16;
}
}
我需要这样使用它:
final static ColorIcon myMenuIcon = new ColorIcon("-155");
我收到错误“iconColor 无法解析为变量” 谢谢。
最佳答案
您需要存储iconColor
从你的构造函数到 instance variable ,或field :
public class ColorIcon implements Icon {
private final String iconColor; // add an instance variable/field - see footnote †
ColorIcon(String iconColor) {
this.iconColor = iconColor; // set the field
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(Color.decode(this.iconColor)); // added "this" for clarity
g.drawRect(7, 5, 11, 11);
g.fillRect(7, 5, 11, 11);
}
/*the rest of your class*/
}
实例变量允许您存储封装的“状态”,您可以在由外部代码独立调用的方法中读取和写入这些“状态”。我建议您阅读The Java Tutorials > Declaring Member Variables了解有关构造类的更多信息。
但是,在你的类里面,我不确定我会这样构造它。尝试Color.decode
可能会更好在构造函数内部调用,并将该字段存储为 Color
- 这样,如果有NumberFormatException
,调用者将立即被告知,而不是在稍后的某个(任意)点 paintIcon
称为:
public class ColorIcon implements Icon {
private final Color iconColor; // add an instance variable/field - see footnote †
ColorIcon(String nm) {
this.iconColor = Color.decode(nm); // set the field
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(this.iconColor); // added "this" for clarity
g.drawRect(7, 5, 11, 11);
g.fillRect(7, 5, 11, 11);
}
/*the rest of your class*/
}
† 看来你永远不会更改实例变量 iconColor
我也做到了final
为了防止其他点的意外突变 - 如果需要,您可以删除它
关于java - 如何将值传递给构造函数并从同一类中的方法使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32585708/