java - 如何将值传递给构造函数并从同一类中的方法使用它?

标签 java class graphics icons

如何将颜色变量传递给下面的类?我想以 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/

相关文章:

class - 如何将 findAll 方法与 Doctrine 中的类一起使用?

javascript - D3 圆弧的一侧

math - 使用给定的一组点扭曲图像的简单方法是什么?

java - 设置 JCombobox 中项目的高度

java - 与后端数据结构同步的 JTable 设计

java - 将 OBJ 文件中的四边形转换为三角形?

c++ - C++ 中的 union 实际上是一个类吗?

java - 如何从网络服务器异步下载图片

Python 将元素添加到一个实例的列表中也会将其添加到另一个实例的列表中

java - Paint 方法 java - 带轮廓的矩形