如何将JScrollbar的Thumb更改为自定义图像 [英] How to change the Thumb of the JScrollbar to a custom image

查看:101
本文介绍了如何将JScrollbar的Thumb更改为自定义图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我在Image()中有一个适当大小的图像 我想将JScrollBar组件的拇指"或旋钮"更改为该图像.

Say I have an appropriately sized image inside an Image() I want to change the Thumb or Knob of the JScrollBar component to be this image.

我知道我需要对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,只有一个Track.

Right now I don't see any Thumb, only a Track when I try to click around the ScrollBar.

我查看了这篇文章,发现有人推荐您阅读,但他无处可去提及图片,这就是我想出的.

I checked out this article and saw people recommended you read this but nowhere does he mention images so this is what I came up with.

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

Hopefully someone can help me, Thanks!

推荐答案

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

Why are you calling g2g.dispose()? It's destroys Graphics object so it can't to paint thumb. Try to remove this call inside paintThumb method. Here is example of drawing custom thumb :

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

这篇关于如何将JScrollbar的Thumb更改为自定义图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆