javafx的原生组件里面的slider只有一个头,滑动获得一个数值,而我想要一个双头slider,滑动获得一个取值范围,看了一圈没有现成的,于是自己动手做了一个
class TwoHeadSlider(private val minValue:Double, private var startValue:Double, private var endValue:Double, maxValue:Double, private var sliderWidth:Double=100.0):Region() {
private var range = maxValue-minValue
private var pane:Pane = Pane().apply { prefHeight=30.0 }
private var valueList:MutableList<Double> = mutableListOf(startValue,endValue)
private var valueFactory = 0.0
val startValueProperty = SimpleDoubleProperty(0.0)
val endValueProperty = SimpleDoubleProperty(0.0)
init {
valueFactory=String.format("%.2f",(range/sliderWidth)).toDouble()
setListenerValue()
children.addAll(pane)
drawSlider()
}
private fun drawSlider(){
// computeData()
val line = Line(0.0, 15.0, sliderWidth, 15.0)
val start = Rectangle(0.0, 0.0, 10.0, 30.0).apply {
// translateX=BigDecimal((startValue-minValue).toString()).divide(BigDecimal(valueFactory.toString())).toDouble()
translateX = String.format("%.0f",(startValue-minValue)/valueFactory).toDouble()
var oldNodeX = 0.0
var oldMoveX=0.0
setOnMousePressed {
oldNodeX = it.sceneX
oldMoveX=translateX
}
setOnMouseDragged {
val moveX = it.sceneX - oldNodeX
if ((moveX+oldMoveX in 0.0..sliderWidth)||(translateX==sliderWidth&&moveX<0)||(translateX==0.0&&moveX>0))
translateX=moveX+oldMoveX
// println(this.translateX)
//这里之所以不用valueFactory是因为用的话valueFactory会有很多位小数,在这儿会算不出来最大值,有一点误差
valueList[0]=String.format("%.2f",BigDecimal(translateX.toString()).multiply(BigDecimal((range/sliderWidth).toString())).add(BigDecimal(minValue.toString()))).toDouble()
setListenerValue()
}
}
val end = Rectangle(0.0, 0.0, 10.0, 30.0).apply {
translateX=String.format("%.0f",(endValue-minValue)/valueFactory).toDouble()
var oldNodeX = 0.0
var oldMoveX=0.0
setOnMousePressed {
oldNodeX = it.sceneX
oldMoveX=translateX
}
setOnMouseDragged {
val moveX = it.sceneX - oldNodeX
if ((moveX+oldMoveX in 0.0..sliderWidth)||(translateX==sliderWidth&&moveX<0)||(translateX==0.0&&moveX>0))
translateX=moveX+oldMoveX
// println(this.translateX)
// valueList[1]=BigDecimal(translateX.toString()).multiply(BigDecimal(valueFactory.toString())).add(BigDecimal(minValue.toString())).toDouble()
valueList[1]=String.format("%.2f",BigDecimal(translateX.toString()).multiply(BigDecimal((range/sliderWidth).toString())).add(BigDecimal(minValue.toString()))).toDouble()
setListenerValue()
}
}
pane.children.addAll(line,start,end)
}
private fun setListenerValue(){
val list = mutableListOf<Double>().apply {
for (s in valueList )
add(s)
}
list.sort()
startValueProperty.value=list[0]
endValueProperty.value=list[1]
}
fun gainStartValue():Double{
return startValueProperty.value
}
fun gainEndValue():Double{
return endValueProperty.value
}
}
效果: