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

How do I pass a value to a constructor and use it from a method in the same class?

如何将颜色变量传递给以下 class?我想以 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 cannot be resolved to a variable" 谢谢。

您需要将构造函数中的 iconColor 存储到 instance variable, or 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*/
}

实例变量允许您存储封装的"state",您可以在外部代码独立调用的方法中读写。我建议您阅读 The Java Tutorials > Declaring Member Variables 以了解有关结构化 classes 的更多信息。

但是,在您的 class 中,我不确定是否会像这样构建它。尝试在构造函数中调用 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以防止意外其他点的突变 - 如果需要,您可以删除它

在实例变量中存储 iconColor

package com.epox.cmc.core.util;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import javax.swing.Icon;

public class ColorIcon implements Icon {
    String iconColor ;
    ColorIcon(String iconColor) {
        this.iconColor = 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;
    }
}