0

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?

Community
  • 1
  • 1
Luis Fernandez
  • 539
  • 1
  • 4
  • 24
  • Why do you want to do that? That dotted line is there to let the user know which component has the input focus Without it, the user has no idea which component will receive keyboard inputs. – FredK Nov 30 '19 at 19:49

1 Answers1

0

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);
George Z.
  • 6,643
  • 4
  • 27
  • 47
  • I'd prefer if the slider was still focusable so it could be controled with the keys instead of just the mouse. – Luis Fernandez Nov 30 '19 at 18:50
  • @LuisFernandez I have edited my answer. My previous answer was totally wrong. I thought the method was `setFocusPainted()` and I instantly posted. :( – George Z. Nov 30 '19 at 20:23