How to hide the knob of jSlider?

对着背影说爱祢 提交于 2019-12-02 02:04:46

To hide the knob, override the UIManager's Slider.horizontalThumbIcon property with an blank icon, like this:

public static void main(String[] args) throws Exception {

    UIManager.getLookAndFeelDefaults().put("Slider.horizontalThumbIcon",new Icon(){
        @Override
        public int getIconHeight() {
            return 0;
        }
        @Override
        public int getIconWidth() {
            return 0;
        }
        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
            //do nothing
        }
    });

    JFrame f = new JFrame();
    JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 15);
    slider.setMajorTickSpacing(10);
    slider.setMinorTickSpacing(1);
    slider.setPaintTicks(true);
    slider.setPaintLabels(true);

    f.add(slider);
    f.setSize(200,200);
    f.setVisible(true);

}

The UIManager solution only works in the Metal LAF from what I can tell.

If you want to change the behavour of the UI then you need to change the UI. In this case you would need to the BasicSliderUI (or one of its sub classes). Then I believe you would need to override the paintThumb() method.

A solution with a different BasicSliderUI looks like this:

public class SuperSlider extends JSlider {
    public SuperSlider(int min, int max, int value) {
        super(min,max,value);
        setUI(new SuperSliderUI(this));
    }
    private class SuperSliderUI extends BasicSliderUI {
        @Override
        public void paintThumb(Graphics g) {
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!