【发布时间】:2019-08-16 08:37:24
【问题描述】:
我有一个名为 theLayers 的 ArrayList,它存储点(层)的集合,我希望每个层都有不同的颜色。在 for 循环的每次迭代中,我将图形设置为新颜色并绘制每个不同层的点。但是,在调试时,我注意到这些点被设置为最后生成的颜色。
我已经尝试将随机颜色分配放置在代码中的不同位置,并且我已经调试了代码以确保在每次迭代期间颜色确实会发生变化。
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.ArrayList;
import javax.swing.JPanel;
public class Drawer extends JPanel {
private ArrayList<ArrayList<Point>> theLayers;
public Drawer() {
this(new ArrayList<ArrayList<Point>>());
}
public Drawer(ArrayList<ArrayList<Point>> coordinates) {
this.theLayers = new ArrayList<ArrayList<Point>>(coordinates);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(3));
for(ArrayList<Point> coordinates:theLayers) {
int R = (int) (Math.random( )*256);
int G = (int)(Math.random( )*256);
int B= (int)(Math.random( )*256);
Color randomColor = new Color(R, G, B);
g2d.setColor(randomColor);
for (int i = 0; i < coordinates.size(); i++) {
g2d.drawLine(coordinates.get(i).x, coordinates.get(i).y,
coordinates.get(i).x, coordinates.get(i).y);
}
}
}
}
我希望每一层的颜色都不同,而不是相同的颜色。谢谢。
【问题讨论】:
-
1) 为了尽快获得更好的帮助,edit 添加minimal reproducible example 或Short, Self Contained, Correct Example。 2) 使用逻辑一致的缩进代码行和块的形式。缩进是为了让代码流更容易理解!大多数 IDE 都有专门用于格式化代码的键盘快捷键。
-
您不应该在 paintComponent() 方法中生成随机颜色。您无法控制 Swing 何时确定组件需要重新绘制。当您将每个对象添加到 ArrayList 时,颜色应该是随机的并存储在 ArrayList 中。这意味着您需要一个自定义对象,其中包含您要绘制的颜色和对象。查看Custom Painting Approaches 中的
DrawOnComponent示例,了解此方法的工作示例。 -
@camickr 我按照你说的做了并创建了一个自定义对象......但这并没有解决我的问题。
-
@Hossmeister, 1) 你的minimal reproducible example 在哪里证明问题? 2) 如果我们看不到代码,您希望我们如何提供帮助? 3) 但更重要的是,您需要学习如何调试自己的代码,那么您的代码与您给出的工作示例代码有何不同?