Remove Arrows from Swing Scrollbar in JScrollPane

后端 未结 4 1446
半阙折子戏
半阙折子戏 2021-01-14 11:08

I would like to remove the scrollbar arrow buttons from a scrollbar in a JScrollPane. How would I do this?

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 11:56

    This is the way i went.

    1. Set the scrollbar policy of the scrollbar you want to hide as never
    2. Mimic this behavior with a MouseWheelListener

    This method:

    • Is fast to implement with very few lines of code.
    • Retains the benefits of the L&F.
    • Will remove both the buttons and the bar.

    Below is a sample code for removing the verticall scroll bar.

    JScrollPane myScrollPane = new JScrollPane();
    
    //remove the scroll bar you don't want
    myScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
    
    JTextPane myJTextArea = new JTextPane();
    
    //myScrollPane.setViewportView(myJTextArea);
    
    myScrollPane.addMouseWheelListener(new MouseWheelListener() {
    
       //this will mimick the behavior of scrolling
       public void mouseWheelMoved(MouseWheelEvent e) {
                JScrollBar scrollBar =  myScrollPane.getVerticalScrollBar();
                //capturing previous value
                int previousValue = scrollBar.getValue();
    
                int addAmount;
    
                //decide where the wheel scrolled
                //depending on how fast you want to scroll
                //you can chane the addAmount to something greater or lesser
    
                if(e.getWheelRotation()>0) {
                    addAmount = 2;
                }else {
                    addAmount = -2;
                }
    
                //set the new value 
                scrollBar.setValue(previousValue + addAmount);
            }
        });
    

提交回复
热议问题