2

I am making a custom JScrollBar.

ScrollBar.java

public class ScrollBar extends JScrollBar {
    ScrollBar() {
        super();
        setUI(new CustomScrollBarUI());
    }
}

CustomScrollBarUI.java

public class CustomScrollBarUI extends BasicScrollBarUI {
    @Override
    protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) {
        Graphics2D g2d = (Graphics2D) g;
        g.setColor(Color.BLACK);
        g2d.fill(trackBounds);
        g2d.draw(trackBounds);
    }
    @Override
    protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.WHITE);
        g2d.fill(thumbBounds);
        g2d.draw(thumbBounds);
    }
}

However this leaves a white trail when scrolling down but clears when scrolling up.

I have tried quite a few things.

  1. Add super.method()

This square I'm animating is leaving a trail behind it, can anyone work out why?

Repaint leaves trail

oval leaves the trail

So I added super.paintThumb(g, c, thumbBounds) and super.paintTrack(g, c, trackBounds) to both but nothing changed.

  1. Clear the previous rectangle

https://community.oracle.com/thread/1265963

Added a bunch of variables to store the previous position

double last_posx = -1d;
double last_posy = -1d;
double last_posw = -1d;
double last_posh = -1d;

and clear the previous rectangle

if (last_posx != -1d) {
    g.clearRect((int) last_posx, (int) last_posy, (int) last_posw, (int) last_posh);
}

This causes the effect to increase more, so there is more white that is left behind.

  1. Repaint the track

This one I thought of myself. So I added super.paintTrack(g, c, super.getTrackBounds()) to repaint the track before the thumb is painted to try and clear the previous thumbs.

This resulted in the same effect as 1.

So what do I do to remove the white trail left behind?

EDIT

As mentioned by LuxxMiner, this solved it but I would like to know why.

CustomScrollBarUI.java

public class CustomScrollBarUI extends BasicScrollBarUI {
    @Override
    protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) {
        Graphics2D g2d = (Graphics2D) g;
        g.setColor(Color.BLACK);
        g2d.fill(trackBounds);
        g2d.draw(trackBounds);
    }
    @Override
    protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.WHITE);
        g2d.fill(thumbBounds);
//      g2d.draw(thumbBounds);
    }
}
Community
  • 1
  • 1
Moon Cheesez
  • 2,489
  • 3
  • 24
  • 38

0 Answers0