2

假设我在其中有一个适当大小的图像,Image() 我想将JScrollBar组件的 Thumb 或 Knob 更改为该图像。

我知道我需要子类化ScrollBarUI

这就是我现在所处的位置。

public class aScrollBar extends JScrollBar {

    public aScrollBar(Image img) {
        super();
        this.setUI(new ScrollBarCustomUI(img));
    }

    public class ScrollBarCustomUI extends BasicScrollBarUI {

        private final Image image;

        public ScrollBarCustomUI(Image img) {
            this.image = img;
        }

        @Override
        protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
            Graphics2D g2g = (Graphics2D) g;
            g2g.dispose();
            g2g.drawImage(image, 0, 0, null);
            super.paintThumb(g2g, c, thumbBounds);
        }

        @Override
        protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) {
            super.paintTrack(g, c, trackBounds);
        }


        @Override
        protected void setThumbBounds(int x, int y, int width, int height) {
            super.setThumbBounds(0, 0, 0, 0);
        }


        @Override
        protected Dimension getMinimumThumbSize() {
            return new Dimension(0, 0);
        }

        @Override
        protected Dimension getMaximumThumbSize() {
            return new Dimension(0, 0);
        }
    }
}

现在我没有看到任何 Thumb,当我尝试在 ScrollBar 周围单击时只有一个 Track。

我查看了这篇文章,看到有人推荐你阅读这篇文章,但他没有提到图片,所以这就是我想出的。

希望有人可以帮助我,谢谢!

4

2 回答 2

0

你为什么打电话g2g.dispose()?它会破坏 Graphics 对象,因此无法绘制拇指。尝试在paintThumb方法中删除此调用。这是绘制自定义拇指的示例:

@Override
    protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
        if (thumbBounds.isEmpty() || !scrollbar.isEnabled()) {
            return;
        }
        g.translate(thumbBounds.x, thumbBounds.y);
        g.drawRect(0, 0, thumbBounds.width - 2, thumbBounds.height - 1);
        AffineTransform transform = AffineTransform.getScaleInstance((double) thumbBounds.width
                / thumbImg.getWidth(null), (double) thumbBounds.height / thumbImg.getHeight(null));
        ((Graphics2D) g).drawImage(thumbImg, transform, null);
        g.translate(-thumbBounds.x, -thumbBounds.y);
    }
于 2014-02-13T21:36:22.770 回答
0

问题是:

g2g.drawImage(image, 0, 0, null);

您必须使用当前拇指位置作为起始绘图点。我想一定是thumbRect.x和thumbRect.y,所以:

g2g.drawImage(image, thumbRect.x, thumbRect.y, null); should work.

另外,我不确定您是否调用了paintThumb 中的超级方法。那条线不会覆盖您自定义的东西吗?

并且:应该忽略 dispose 的调用。

于 2012-03-30T23:01:25.930 回答