2

I want to create scrollpane like on this picture: enter image description here

With arrows on component sides and with no scrollbar visible. Only horizontal scrolling is needed. Can It be done with JScrollPane?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Marco
  • 582
  • 1
  • 6
  • 17

1 Answers1

6

You can make you own component by using a scrollpane and by creating your own buttons that will use the Actions of the scrollbar:

import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;

public class ScrollPaneSSCCE extends JPanel
{
    public ScrollPaneSSCCE()
    {
        setLayout( new BorderLayout() );

        JTextArea textArea = new JTextArea(1, 80);
        textArea.setText("Hopefully this will answer your question");
        JScrollPane scrollPane = new JScrollPane( textArea );
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        add(scrollPane);

        JScrollBar horizontal = scrollPane.getHorizontalScrollBar();

        BasicArrowButton west = new BasicArrowButton(BasicArrowButton.WEST);
        west.setAction( new ActionMapAction("", horizontal, "negativeUnitIncrement") );
        add(west, BorderLayout.WEST);

        BasicArrowButton east = new BasicArrowButton(BasicArrowButton.EAST);
        east.setAction( new ActionMapAction("", horizontal, "positiveUnitIncrement") );
        add(east, BorderLayout.EAST);
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("ScrollPaneSSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new ScrollPaneSSCCE(), BorderLayout.NORTH);
        frame.setSize(100, 100);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

You will also need to use the Action Map Action class.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • It works great, thanks! Small question: how can I make those buttons invisible when there is nothing to scroll (entire content fits on the screen)? – Marco Apr 06 '13 at 09:16
  • Add a ComponentListener to the scrollPane and listen for the componentResized() method. Then you check the preferred size of the component added to the scrollpane and the size of the scrollpane. When the preferred size is greater you show the buttons else you hide them. – camickr Apr 06 '13 at 15:45