情况:
我制作了一个可以打开和关闭灯光的Java应用程序。现在我需要改变灯光,这必须发生在class
ColorLamp 中。正常"黄色"灯光放在class
灯中。 class
Colorlamp 是subclass
Lamp 的class
。
问题:
如何制作它以便我可以通过class
ColorLamp 中的某些代码更改灯泡颜色?
如何使用class
ColorLamp 更改灯泡的颜色?
来自class
Lamp (更新)的代码:
public class Lamp
{
protected Color kleur = Color.YELLOW;
public static final boolean AAN = true;
public static final boolean UIT = false;
// instance variable
protected boolean aanUit;
// constructor
public Lamp()
{
// init instance variable
this.aanUit = UIT;
}
public void setAanUit(boolean aanUit)
{
this.aanUit = aanUit;
}
// switch
public void switchAanUit()
{
this.aanUit = !this.aanUit;
}
public boolean getAanUit()
{
return this.aanUit;
}
public String toString()
{
String res = "Lamp: ";
if (aanUit)
{
res = res + "AAN";
}
else
{
res = res + "UIT";
}
return res;
}
public void teken(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(5));
g2.drawOval(208, 100, 50, 50); // ronde lamp
g2.drawLine(220, 150, 220, 175); // linker kant
g2.drawLine(245, 150, 245, 175); // rechter kant
g2.drawLine(220, 175, 235, 200); // linksonder hoek
g2.drawLine(235, 200, 245, 175); // rechtsonder hoek
if(aanUit == true)
{
ColorLamp kleurlamp = new ColorLamp();
g.setColor(kleurlamp.getColor());
}
else
{
g.setColor(Color.WHITE);
}
g.fillOval(208, 100, 50, 50);
g.setColor(Color.BLACK);
}
}
这里是当前class
ColorLamp 的代码(有效,但不是如何):
public class ColorLamp extends Lamp
{
protected Color kleur = Color.GREEN;
public Color getColor()
{
return kleur;
}
}
可能的正确代码class
ColorLamp :
package lamp;
import java.awt.*;
public class ColorLamp extends Lamp
{
protected Color kleur = Color.GREEN;
public ColorLamp(Color kleur)
{
super();
this.kleur = kleur;
}
public Color getKleur()
{
return this.kleur;
}
public void setKleur(Color kleur)
{
this.kleur = kleur;
}
public String toString()
{
String res = "Lamp: ";
if(super.getAanUit())
{
res = res + "ÄAN";
}
else{
res = res + "UIT";
}
return res + kleur.toString();
}
}
答案 0 :(得分:2)
您应该做的是让所有Lamp
个对象都有Color
。 Lamp
类本身将具有Color.Yellow
,并且无法从其他类更改。
public class Lamp
{
protected Color kleur = Color.YELLOW;
/// Other things...
public void teken(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
// Draw the lamp parts
if(aanUit == true)
{
g.setColor(this.kleur); // Set color here
}
else
{
g.setColor(Color.WHITE);
}
g.fillOval(208, 100, 50, 50);
g.setColor(Color.BLACK);
}
}
然后在ColorLamp
中,您可以删除 private Color kleur;
并使用继承的protected Color kleur
字段。
要在绘制灯泡后更改颜色,您需要repaint
组件。