JScrollPane有滚动箭头但没有滚动条

时间:2013-04-05 16:35:07

标签: java swing jscrollpane custom-component jscrollbar

我想在这张图片上创建滚动窗格: enter image description here

组件侧有箭头,没有可见的滚动条。只需要水平滚动。可以用JScrollPane完成吗?

1 个答案:

答案 0 :(得分:6)

您可以使用滚动窗格创建自己的组件,并创建自己的按钮,使用滚动条的操作:

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();
            }
        });
    }
}

您还需要使用Action Map Action类。