我正在尝试修改JSlider,以便在单击轨道时出现拇指(旋钮)。我正在调整找到here的代码来实现这一目标。基本上,我通过最初将其大小设置为0来隐藏拇指。当鼠标单击轨道时,拇指会更改其大小以便显示。我遇到的问题是轨道也没有出现。但是,一旦单击该轨道,它就会出现。是否有改变拇指(或以某种方式隐藏它)而不改变轨道?任何建议,将不胜感激。
public class SliderUI extends MetalSliderUI {
private boolean displayThumb = false;
private int x = 0;
private int y = 0;
public SliderUI(){
super();
}
@Override
protected Dimension getThumbSize() {
return new Dimension(x, y);
}
@Override
protected void scrollDueToClickInTrack(int direction) {
//keep displaying thumb once true
if(!displayThumb){
x = 15;
y = 20;
displayThumb = true;
}
int value = slider.getValue();
if (slider.getOrientation() == JSlider.HORIZONTAL) {
value = this.valueForXPosition(slider.getMousePosition().x);
} else if (slider.getOrientation() == JSlider.VERTICAL) {
value = this.valueForYPosition(slider.getMousePosition().y);
}
slider.setValue(value);
}
}
更新:我也尝试过类似的方法,使用paintThumb(),但无济于事。我收到空指针异常错误。这是我试过的:
public class SliderUI extends MetalSliderUI {
private boolean displayThumb = false;
protected static Icon horizThumbIcon;
protected static Icon vertThumbIcon;
private static Icon SAFE_HORIZ_THUMB_ICON;
private static Icon SAFE_VERT_THUMB_ICON;
public SliderUI(){
super();
}
private static Icon getHorizThumbIcon() {
if (System.getSecurityManager() != null) {
return SAFE_HORIZ_THUMB_ICON;
} else {
return horizThumbIcon;
}
}
private static Icon getVertThumbIcon() {
if (System.getSecurityManager() != null) {
return SAFE_VERT_THUMB_ICON;
} else {
return vertThumbIcon;
}
}
@Override
public void paintThumb(Graphics g) {
//keep displaying thumb once true
if(!displayThumb){
displayThumb = true;
return;
}
Rectangle knobBounds = thumbRect;
g.translate( knobBounds.x, knobBounds.y );
if ( slider.getOrientation() == JSlider.HORIZONTAL ) {
getHorizThumbIcon().paintIcon( slider, g, 0, 0 );
}
else {
getVertThumbIcon().paintIcon( slider, g, 0, 0 );
}
g.translate( -knobBounds.x, -knobBounds.y );
}
@Override
protected void scrollDueToClickInTrack(int direction) {
int value = slider.getValue();
if (slider.getOrientation() == JSlider.HORIZONTAL) {
value = this.valueForXPosition(slider.getMousePosition().x);
} else if (slider.getOrientation() == JSlider.VERTICAL) {
value = this.valueForYPosition(slider.getMousePosition().y);
}
slider.setValue(value);
}
}
答案 0 :(得分:0)
以下是我的问题的简单解决方案:
public class SliderUI extends MetalSliderUI {
private boolean displayThumb = false;
public SliderUI(){
super();
}
@Override
public void paintThumb(Graphics g) {
if(displayThumb){
super.paintThumb(g);
}
}
@Override
protected void scrollDueToClickInTrack(int direction) {
//keep displaying thumb once true
if(!displayThumb){
displayThumb = true;
}
int value = slider.getValue();
if (slider.getOrientation() == JSlider.HORIZONTAL) {
value = this.valueForXPosition(slider.getMousePosition().x);
} else if (slider.getOrientation() == JSlider.VERTICAL) {
value = this.valueForYPosition(slider.getMousePosition().y);
}
slider.setValue(value);
}
}