gpt4 book ai didi

java - 我想在满足条件时更改 PaintComponent() 对象的颜色

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

我似乎无法理解这一点,我知道涉及到 repaint() 但不知道如何使用它。这是我的代码

public CarPanel()
{
repaint();
rects = new Rectangle[]
{
new Rectangle(25, 35, 30, 80, Color.GREEN,"8"),
new Rectangle(65, 35, 30, 80, Color.GREEN,"7"),
new Rectangle(105, 35, 30, 80, Color.GREEN,"6"),
new Rectangle(145, 65, 30, 50, Color.GREEN,"2"),
new Rectangle(185, 65, 30, 50, Color.green,"1"),
new Rectangle(25, 170, 30, 50, Color.GREEN,"13"),
new Rectangle(65, 170, 30, 50, Color.GREEN,"12"),
new Rectangle(105, 170, 30, 50, Color.GREEN,"11"),
new Rectangle(145, 170, 30, 50, Color.GREEN,"3"),
new Rectangle(190, 160, 92, 80, Color.BLACK,"Attendant Station"),
new Rectangle(25, 280, 30, 50, Color.GREEN,"15"),
new Rectangle(65, 280, 30, 50, Color.GREEN,"14"),
new Rectangle(105, 280, 30, 80, Color.GREEN,"10"),
new Rectangle(145, 280, 30, 80, Color.GREEN,"9"),
new Rectangle(185, 280, 30, 50, Color.GREEN,"5"),
new Rectangle(225, 280, 30, 50, Color.GREEN,"4")
};
}//end carPark

public void changeShapeColor(){

}

@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.white);

for (Rectangle rect : rects) {
g.setColor(Color.BLACK);
g.drawString(rect.number, rect.x, rect.y);
g.setColor(rect.color);
g.fillRect(rect.x, rect.y, rect.w, rect.h);
}//end for
}//end paintComponent
}//end JPanel

当代码中其他地方满足条件时,我想将颜色从绿色更改为红色。非常感谢任何帮助:)

最佳答案

public void changeShapeColor(Color newColor) {
for (Rectangle rect : rects) {
rect.color = newColor;
}
}

然后在条件发生更改时调用 changeShapeColor 方法。并确保您的组件已失效,因此它将被重绘。

关于java - 我想在满足条件时更改 PaintComponent() 对象的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27190000/

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