JScrollBar自定义滚动条ui图形离开

时间:2015-11-15 15:17:37

标签: java swing graphics2d jscrollbar

我正在制作一个自定义的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);
    }
}

然而,当向下滚动时会留下白色痕迹,但在向上滚动时会清除。

我尝试了很多东西。

  1. 添加super.method()
  2. This square I'm animating is leaving a trail behind it, can anyone work out why?

    Repaint leaves trail

    oval leaves the trail

    所以我添加了super.paintThumb(g, c, thumbBounds)super.paintTrack(g, c, trackBounds),但没有任何改变。

    1. 清除上一个矩形
    2. https://community.oracle.com/thread/1265963

      添加了一堆变量来存储以前的位置

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

      并清除前一个矩形

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

      这会使效果增加更多,因此留下更多白色。

      1. 重新制作曲目
      2. 这个我想到了自己。因此,在绘制拇指之前,我添加了super.paintTrack(g, c, super.getTrackBounds())来重新绘制轨道,以尝试清除之前的拇指。

        这导致与1相同的效果。

        那么我该如何去除留下的白色痕迹呢?

        修改

        如LuxxMiner所述,这解决了它,但我想知道原因。

        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);
            }
        }
        

0 个答案:

没有答案