javaswingjslider

How to remove the dotted line from a JSlider when it gets focus?


I need to remove the dotted line that appears around my JSlider whenever it gets focus:

dottedLine

This is my code:

private JSlider getSlVolume() {
   if (slVolume == null) {
      slVolume = new JSlider();
      slVolume.addChangeListener(new ChangeListener() { 
         public void stateChanged(ChangeEvent arg0) {
            mP.setVolume(slVolume.getValue(), slVolume.getMaximum());
            txtVol.setText(String.valueOf(slVolume.getValue())); 
         }
      });
      slVolume.setPaintLabels(true);
      slVolume.setPaintTicks(true);
      slVolume.setMinorTickSpacing(10);
      slVolume.setMajorTickSpacing(20);
   }
   return slVolume;
}

I've tried using UIManager.put("Slider.focus", UIManager.get("Slider.background")); as per suggested here but it doesn't work for me. Any suggestions?


Solution

  • The only way I managed to achieve it, is to change its UI (via the setUI method) and @Override paintFocus method. It depends on what look and feel you are using. If you are using java's default look and feel, it uses BasicUI to all components. So, in order to change it:

    BasicSliderUI sliderUI = new BasicSliderUI(slider) {
        @Override
        public void paintFocus(Graphics g) {
            // dont paint focus
        }
    };
    slider.setUI(sliderUI);
    

    However, as I see you do not use this look and feel. Since you do not mention what LAF you are using, I will show you how you change it in Windows Look & Feel (you might get an access restriction warning for using a class from com.sun.java.swing.plaf.windows package):

    JSlider slider = new JSlider();
    WindowsSliderUI s = new WindowsSliderUI(slider) {
        @Override
        public void paintFocus(Graphics g) {
            // dont paint focus
        }
    };
    slider.setUI(s);