簡體   English   中英

如何將JScrollbar的Thumb更改為自定義圖像

[英]How to change the Thumb of the JScrollbar to a custom image

假設我在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);
        }
    }
}

現在,當我嘗試單擊ScrollBar時,看不到任何Thumb,只有一個Track。

我檢查了這個文章,看到的人推薦你讀這個 ,但無處他提到圖像,所以這是我想出了。

希望有人可以幫助我,謝謝!

為什么要調用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);
    }

問題是:

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

您必須使用當前的拇指位置作為起始繪圖點。 我認為它必須是thumbRect.x和thumbRect.y,因此:

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

此外,我不確定您是否會調用paintThumb中的超級方法。 那行不會覆蓋您自定義的內容嗎?

並且:處置呼叫應被忽略。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM