[java]代码库
package com.sxt.img;
import java.awt.BorderLayout;
import java.awt.Component;
import java.util.Dictionary;
import java.util.Hashtable;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class JSliderTest
{
JFrame frame = new JFrame("JSlider测试");
Box sliderBox = new Box(BoxLayout.Y_AXIS);
JTextField showValue = new JTextField();
ChangeListener listener = null;
public void init()
{
listener = new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e)
{
JSlider slider = (JSlider) e.getSource();
showValue.setText("当前值:" + slider.getValue());
}
};
JSlider slider = new JSlider();
addSlider(slider, "普通滚动条");
slider = new JSlider();
slider.setExtent(30);// 设置滚动条的保留区为30
addSlider(slider, "保留区为30");
slider = new JSlider(30, 200);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
addSlider(slider, "带刻度");
slider = new JSlider();
slider.setSnapToTicks(true);// 设置滚动条只停留在有刻度的地方
slider.setPaintTicks(true);
slider.setMinorTickSpacing(5);
slider.setMajorTickSpacing(100);
addSlider(slider, "滑块停在刻度处");
slider = new JSlider();
slider.setPaintTrack(false);
slider.setPaintTicks(true);
slider.setMinorTickSpacing(5);
slider.setMajorTickSpacing(100);
addSlider(slider, "没有滑动轨道的滚动条");
slider = new JSlider();
slider.setPaintTicks(true);
slider.setMajorTickSpacing(100);
slider.setMinorTickSpacing(5);
slider.setInverted(true);
addSlider(slider, "设置没有反向的滚动条");
slider = new JSlider();
slider.setPaintTicks(true);
slider.setMinorTickSpacing(5);
slider.setMajorTickSpacing(100);
slider.setPaintLabels(true);// 设置刻度标签
addSlider(slider, "数值刻度标签");
slider = new JSlider();
slider.setPaintTicks(true);
slider.setMinorTickSpacing(5);
slider.setMajorTickSpacing(100);
slider.setPaintLabels(true);
Dictionary<Integer, Component> labels = new Hashtable<Integer, Component>();
labels.put(0, new JLabel("A"));
labels.put(20, new JLabel("B"));
labels.put(40, new JLabel("C"));
labels.put(60, new JLabel("D"));
labels.put(80, new JLabel("E"));
labels.put(100, new JLabel("F"));
slider.setLabelTable(labels);
addSlider(slider, "JLable标签");
frame.add(sliderBox);
frame.add(showValue, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void addSlider(JSlider slider, String description)
{
slider.addChangeListener(listener);
Box box = new Box(BoxLayout.X_AXIS);
JLabel label = new JLabel(description);
box.add(label);
box.add(slider);
sliderBox.add(box);
}
public static void main(String[] args)
{
new JSliderTest().init();
}
}