Java Swing JSlider(垂直)更改 thumbRect 会弄乱滑块控件

Java Swing JSlider (Vertical) changing thumbRect messes up slider control

我正在尝试覆盖 paintThumb 以显示图形滑块缩略图。只要我不弄乱图像的大小并让它根据拇指的现有大小进行绘制,拇指图像和滑块就可以正常工作。如果我更改 thumbRect 或我的图像的大小,我将无法抓住拇指或移动滑块不再有效。这是一个垂直的JSlider。

注意:感谢 trashgod 提供的解决方案。见代码。
注 2:更新为现在是一个可接受的工作示例。
注 3:最初的问题是由在 paintThumb 中调整大小引起的。

这是滑块:

sliders[channel].setUI(new customSliderHandle(sliders[channel], busType));

这是class:

private static class customSliderHandle extends BasicSliderUI {

    String sBusType;
    Image image;

    public customSliderHandle(JSlider slider, String busType) {
        super(slider);

        sBusType = busType;

        try {
            if(sBusType.equals("ch")) {
                //noinspection ConstantConditions
                image = ImageIO.read(getClass().getClassLoader().getResource("web/images/black-slider.png"));
            } else {
                //noinspection ConstantConditions
                image = ImageIO.read(getClass().getClassLoader().getResource("web/images/yellow-slider.png"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void calculateThumbSize() {
        super.calculateThumbSize();

        //// Fixed!!!
        thumbRect.setSize(20, 40);
    }

    @Override
    public void paintThumb(Graphics g) {

        ///// This was the original problem. Move into
        ///// calculateThumbSize() resolved the problem.
        ///// thumbRect.setSize(20, 40);

        int x = thumbRect.x;
        int y = thumbRect.y;
        int width = thumbRect.width;
        int height = thumbRect.height;
        g.drawImage(image, x, y, width, height, null);
    }
}

在调用 paintThumb() 时,BasicSliderUI has already calculated thumbRect based on the result of getThumbSize(). Moreover, because of its unknown latency, you should not invokeImageIO.read() inside paint(). Instead, load the image asynchronously, perhaps using SwingWorker as shown here,并在 getThumbSize() 的实现中使用图像的尺寸。请注意,如果您的 image 不是正方形,则应考虑 getOrientation() 的结果。