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

时间:2015-09-15 12:08:14

标签: 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无法解析为变量” 谢谢。

2 个答案:

答案 0 :(得分:0)

您需要将构建函数中的iconColor存储到instance variablefield

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*/
}

实例变量允许您存储封装的&#34;状态&#34;您可以在外部代码独立调用的方法中读取和写入。我建议您阅读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以防止其他点发生意外突变 - 你可以如果您需要

,请将其删除

答案 1 :(得分:-1)

将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;
    }
}