【问题标题】:Java Swing JSlider (Vertical) changing thumbRect messes up slider controlJava Swing JSlider (Vertical) 改变 thumbRect 搞乱了滑块控件
【发布时间】:2015-08-25 16:05:16
【问题描述】:

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

注意:感谢垃圾神提供的解决方案。见代码。
注 2:已更新为现在可接受的示例。
注意 3:原始问题是由于在paintThumb 中调整大小造成的。

这是滑块:

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

课程如下:

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

【问题讨论】:

    标签: java swing jslider


    【解决方案1】:

    在调用paintThumb()时,BasicSliderUI已经根据getThumbSize()的结果计算出thumbRect。此外,由于它的未知延迟,您不应在paint() 内调用ImageIO.read()。相反,异步加载图像,可能使用SwingWorker,如here 所示,并在getThumbSize() 的实现中使用图像的尺寸。请注意,如果您的image 不是正方形,则应考虑getOrientation() 的结果。

    【讨论】:

    • 我非常感谢 SO 和那些提供帮助的人!我只是将 thumbRect.setSize(20,40) 放在 calculateThumbSize() 覆盖中,它就起作用了。不确定如何简化图像处理,但这绝对是答案。我会更新我的 OP
    • 如果我将 ImageIO 移出paintThumb 并移入父方法 (customSliderHandle) 并将声明放入类中(就像我对 sBusType 所做的那样)会好吗?
    • @JohnSmith:在构造函数中传递引用听起来不错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多