问题描述
最近做一个能够调节范围的东西,类似http://www.zapatec.com/website/main/products/slider/demo.jsp#zpslider/slider2.html中的例子,但这个例子是网页中的,不是在Swing中实现的。一般Swing的JSlider只有一个滑块,我的想法是把两个JSlider实例设置成透明叠加放在同一个位置,但这样做,虽然能够显示两个滑块,但只有一个滑块能够移动。希望知道的朋友能够给出一个滑杆上有两个滑块的例子。我的源代码如下:importjavax.swing.Box;importjavax.swing.BoxLayout;importjavax.swing.JFrame;importjavax.swing.JSlider;importjavax.swing.JTextField;importjavax.swing.event.ChangeEvent;importjavax.swing.event.ChangeListener;publicclassDoubleSliderextendsJFrame{BoxsliderBox=newBox(BoxLayout.Y_AXIS);JTextFieldshowVal=newJTextField();ChangeListenerlistener;/***Launchtheapplication*@paramargs*/publicstaticvoidmain(Stringargs[]){try{DoubleSliderframe=newDoubleSlider();frame.setVisible(true);}catch(Exceptione){e.printStackTrace();}}/***Createtheframe*/publicDoubleSlider(){super();setBounds(100,100,500,375);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);getContentPane().setLayout(null);init();//finalJButtonbutton=newJButton();//button.setText("NewJButton");//button.setBounds(10,304,472,29);//getContentPane().add(button);}publicvoidinit(){listener=newChangeListener(){publicvoidstateChanged(ChangeEventevent){//取出滑动条的值,并在文本中显示出来JSlidersource=(JSlider)event.getSource();showVal.setText("当前滑动条的值为:"+source.getValue());}};JSliderslider1=newJSlider();JSliderslider2=newJSlider();addSlider(slider1,slider2,"普通滑动条");//add(sliderBox,BorderLayout.CENTER);//add(showVal,BorderLayout.SOUTH);showVal.setBounds(10,304,472,29);add(showVal);}publicvoidaddSlider(JSliderslider1,JSliderslider2,Stringdescription){slider1.addChangeListener(listener);slider1.setBounds(10,78,472,29);slider1.setValue(5);slider1.setPaintTrack(false);slider1.setOpaque(false);slider2.addChangeListener(listener);slider2.setBounds(10,78,472,29);slider2.setValue(95);//slider2.setPaintTrack(false);slider2.setOpaque(false);add(slider1);add(slider2);}}
解决方案
解决方案二:
自己定义一个