5

我想使用 JSlider 来浏览一些按时间顺序排列的事件,所以我设置了一个自定义 LabelTable 以便它显示一些日期而不是默认的整数值。我的代码是这样的:

JSlider slider = new JSlider();
...
Date[] dates = getDates();
        slider.setModel(new DefaultBoundedRangeModel(0, 0, 0, dates.length - 1));
        Hashtable<Integer, JLabel> ht = new Hashtable<Integer, JLabel>();
        for (int i = 0; i < dates.length; ++i) {
            JLabel label = new JLabel(DateFormat.getDateInstance().format(dates[i]));
            ht.put(i, label);
        }
        slider.setLabelTable(ht);
        slider.setPaintLabels(true);
        slider.setInverted(true);

如您所见,这很好用: 在此处输入图像描述

但是,如果我想改变滑块的方向,比如说slider.setOrientation(JSlider.HORIZONTAL);,结果如下: 在此处输入图像描述

如果我想每隔一个日期在滑块上方显示一个日期/在滑块下方显示一个日期怎么办?另外,我可以在垂直滑块上的滑块左侧显示标签吗?

问候, 雷米

4

1 回答 1

7

更改标签面(只需应用 RTL 方向):

public static void main ( String[] args )
{
    try
    {
        UIManager.setLookAndFeel ( new NimbusLookAndFeel () );
    }
    catch ( UnsupportedLookAndFeelException e )
    {
        e.printStackTrace ();
    }


    JFrame frame = new JFrame ();

    JSlider slider = new JSlider ( SwingConstants.VERTICAL );
    slider.setPaintLabels ( true );
    slider.setComponentOrientation ( ComponentOrientation.RIGHT_TO_LEFT );

    Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel> ();
    table.put ( 0, new JLabel ( "May 2, 2000" ) );
    table.put ( 25, new JLabel ( "May 3, 2001" ) );
    table.put ( 50, new JLabel ( "May 4, 2002" ) );
    table.put ( 75, new JLabel ( "May 5, 2003" ) );
    table.put ( 100, new JLabel ( "May 6, 2004" ) );
    slider.setLabelTable ( table );

    frame.add ( slider );

    frame.pack ();
    frame.setLocationRelativeTo ( null );
    frame.setVisible ( true );
}

结果:

在此处输入图像描述

要改变标签位置,您必须手动修改它们。例如,这可以通过以下方式完成:

public static void main ( String[] args )
{
    try
    {
        UIManager.setLookAndFeel ( new NimbusLookAndFeel () );
    }
    catch ( UnsupportedLookAndFeelException e )
    {
        e.printStackTrace ();
    }


    JFrame frame = new JFrame ();
    frame.getRootPane ().setBorder ( BorderFactory.createEmptyBorder ( 5, 5, 5, 5 ) );

    JSlider slider = new JSlider ( SwingConstants.HORIZONTAL );
    slider.setPaintLabels ( true );

    Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel> ();
    table.put ( 0, new JLabel ( "May 2, 2000" ) );
    JLabel l2 = new JLabel ( "May 3, 2001" );
    l2.setBorder ( BorderFactory.createEmptyBorder ( 20, 0, 0, 0 ) );
    table.put ( 25, l2 );
    table.put ( 50, new JLabel ( "May 4, 2002" ) );
    JLabel l3 = new JLabel ( "May 5, 2003" );
    l3.setBorder ( BorderFactory.createEmptyBorder ( 20, 0, 0, 0 ) );
    table.put ( 75, l3 );
    table.put ( 100, new JLabel ( "May 6, 2004" ) );
    slider.setLabelTable ( table );

    frame.add ( slider );

    frame.pack ();
    frame.setLocationRelativeTo ( null );
    frame.setVisible ( true );
}

结果:

在此处输入图像描述

当然,您可以改进该代码并根据之前的标签首选高度(取自首选尺寸)在标签创建周期中添加边框,每个甚至运行。

于 2013-02-11T09:03:01.287 回答