我试图覆盖paintThumb以显示图形滑块。只要我不弄乱图像的大小并让它根据拇指的现有尺寸进行绘制,拇指图像和滑块功能就会很好。如果我改变了thumbRect或我的图像的大小,我不能抓住拇指或移动滑块不再工作。这是一个垂直的JSlider。
注意:感谢trashgod解决方案。见代码。
注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);
}
}
答案 0 :(得分:3)
在调用paintThumb()
时,BasicSliderUI
已根据thumbRect
的结果计算出getThumbSize()
。此外,由于其未知延迟,您不应在ImageIO.read()
内调用paint()
。相反,可以使用显示here的SwingWorker
异步加载图像,并在getThumbSize()
的实现中使用图像的尺寸。请注意,如果getOrientation()
不是正方形,则应将image
的结果考虑在内。