对于作业,我需要生成一个“笑脸”面,以便在JPanel的主类中使用,并且必须使用随机颜色。显然我可以在构造函数之外定义颜色,就像我为测试我的主代码所做的那样,但我想知道如何让它在构造函数中工作。 return语句给出错误'inccompatable types:unexpected return value'。
public class Smiley extends JPanel
{
Random rand = new Random();
private int x = 5;
private int y = 5;
private int diameter = 200;
// Smiley constructor takes parameters for 4 colors that will be used to draw the smiley
public Smiley(Color outline, Color face, Color smile, Color eyes)
{
outline = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
face = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
smile = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
eyes = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
return outline; //this doesn't work.
return face;
return smile;
return eyes;
}
// Use this method to draw the smiley face on the panel
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(outline);
g.drawOval(x, y, diameter, diameter);
g.setColor(face);
g.fillOval(x+2, y+2, diameter-4, diameter-4);
g.setColor(eyes);
g.fillOval(x+25, y+66, diameter/3, diameter/3);
g.fillOval(x+125, y+66, diameter/3, diameter/3);
g.setColor(smile);
g.fillArc(x+55, y+105, diameter/3, diameter/3, 180, 180);
}
}
答案 0 :(得分:1)
您唯一需要做的就是将颜色创建为类的实例变量。无需保留对Random
实例的引用。
public class Smiley extends JPanel {
private Color outline;
private Color face;
private Color smile;
private Color eyes;
public Smiley() {
this(new Random());
}
public Smiley(Random rand) {
outline = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
face = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
smile = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
eyes = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
}
public Smiley(Color outline, Color face, Color smile, Color eyes) {
this.outline = Objects.requireNonNull(outline);
this.face = Objects.requireNonNull(face);
this.smile = Objects.requireNonNull(smile);
this.eyes = Objects.requireNonNull(eyes);
}
...
}
第一个(无参数)构造函数将创建一个随机颜色的笑脸 - 并将在每个构造中创建一个新的Random
对象,第二个构造函数将创建一个具有随机颜色的笑脸,允许传递可重用的{ {1}}对象。第三个构造函数将允许使用指定的颜色创建一个Smiley。
答案 1 :(得分:1)
表单Oracle Java文档:
一个类包含被调用以从类蓝图创建对象的构造函数。构造函数声明看起来像方法声明 - 除了它们使用类的名称并且没有返回类型。
因此概念不可能从构造函数返回值。