gpt4 book ai didi

java - 在Java中动态改变区域的颜色

转载 作者:行者123 更新时间:2023-12-02 03:56:02 25 4
gpt4 key购买 nike

早上好,我需要动态更改几个区域的颜色。基本上,我创建了一个类 Ovals ,并在该类中创建了一个区域。在View类中,我创建了一个OvalsArrayList,并向列表中添加了一些区域,并将它们绘制在不同的位置。这是我的意思的源代码:

public class Objects{
Area shape;
public Objects(int x,int y){
this.shape= new Area (new Ellipse2D.Float(x, y, 70, 70));
}

public Color randColor(){
Color[]color = {
Color.red,
Color.BLUE,
Color.cyan,
Color.green,
Color.pink,
Color.black,
Color.LIGHT_GRAY,
Color.magenta,Color.orange,
Color.white,Color.yellow,
Color.darkGray
};
return color[randomPosition(color.length)];
}

}

public class View extends JComponent{
ArrayList<Objects> ob= new ArrayList<Object>();
//stuff...

public View()
{
addObjects();
//other stuff...
}

public void paintComponent(Graphics2D g2)
{
//if I set the color here with the classical g2.setColor(Color.red) every object will be red
drawOvals(g2);
}


public void addObjects(){
for(int i=2;i<10;i++)
ob.add(new Objects(i+10,100));
}


public void drawOvals(Graphics2D g2)
{
if(ob!=null){
for(Objects o:op)
{
//I waant to know for example if there is a way to set the color indipendently for each object
//I tried to put here: *g2.setColor(o.randColor())* but the paintComponent method is called every 10ms so the color changes very rapidly
g2.draw(o.shape);
g2.fill(o.shape);
}
}
}
}

我知道这个问题有点长,但如果您知道如何解决这个问题,请回答!非常感谢!!

最佳答案

您可以为每个椭圆形关联一个颜色:

public class Objects{
Area shape;
Color color;

public Objects(int x,int y){
this.shape= new Area (new Ellipse2D.Float(x, y, 70, 70));
color = randColor();
}
...
}

然后在绘制椭圆之前:

 for(Objects o:op)
{
g2.setColor(o.color);
g2.draw(o.shape);
g2.fill(o.shape);
}

关于java - 在Java中动态改变区域的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35442237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com