I use Netbeans8 and Java7. Inside a JPanel embedded in a JScrollPane I draw a lot of coloured rectangles. When I scroll down via the scroll bar some of the rectangles are shown in strange strips, as illustrated in the following image (specifically, see the blue rectangle).

An example of the strips

I paint rectangles as follows in the class that extends JPanel.

List<Rectangle> rectagles = ...
List<Color> colours = ...

@Override
public void paintComponent(Graphics g) {
    int index = 0;
    int maxX = 0;
    int maxY = 0;
    for (Rectangle r : rectangles) {
        g.setColor(colours.get(index));
        int x = r.x;
        int y = r.y;
        int width = r.width;
        int height = r.height;

        maxX = Math.max(maxX, x + width);
        maxY = Math.max(maxY, y + height);

        g.fillRect(x, y, width, height);
        g.setColor(Color.BLACK);
        g.drawRect(x, y, width, height);
        index++;
    }
    this.setMinimumSize(new Dimension(maxX, maxY));
    this.setMaximumSize(new Dimension(maxX, maxY));
    this.setPreferredSize(new Dimension(maxX, maxY));
}

How can I prevent this annoying situation?

有帮助吗?

解决方案

You need to add:

super.paintComponent(g);

at the top of your paintComponent() method to clear the background before you do your custom painting.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top