How to change Thumb of JScrollbar to a custom image

Say I have an image of the appropriate size inside Image() I want to change the Thumb or Knob of the JScrollBar component this way.

I know that I need to subclass ScrollBarUI

That's where I am now.

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

Right now I don't see a single Thumb, just a track when I try to click on a ScrollBar.

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

Hope someone can help me, thanks!

+2
source share
2 answers

The problem is this:

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

You must use the current position of the thumb as the starting point for the drawing. I think it should be thumbRect.x and thumbRect.y, therefore:

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

In addition, I'm not sure about your call to the super method in paintThumb. Doesn't this line override your configured things?

And: the utility call must be omitted.

0
source

Why are you calling g2g.dispose() ? It destroys the Graphics object, so it cannot draw a thumb. Try removing this call inside the paintThumb method. Here's an example of drawing a 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); } 
0
source

Source: https://habr.com/ru/post/1432296/


All Articles