问题
I have created a Slider using JavaFX. I`m trying to set it up so that it shows time in minutes.
I have been able to setup the the minutes to range from 0 - 60. My problem is my minutes are showing correctly but my seconds are between 0 - 100.
How can I fix this?
Here is how I created the slider
<ScrollPane fx:id="RulerScroll1" hbarPolicy="NEVER" maxHeight="40" minHeight="40" pannable="true" GridPane.columnIndex="1" GridPane.hgrow="ALWAYS" GridPane.rowIndex="2">
<Slider fx:id="Ruler1" majorTickUnit="10" maxHeight="35" min="0" minHeight="35" minorTickCount="4" showTickLabels="true" showTickMarks="true" snapToPixel="true" />
</ScrollPane>
How can I format the values it gives me so that they can appear as minutes and seconds?
回答1:
You could use a StringConverter to display the value of the Slider on another control, and also you can use this converter for the labelFormatterProperty of the Slider.
In the Example
It sets the range of the Slider from 0-3600 and shows the ticks for every 15 minutes in "15:00" format. The value of the Slider is displayed on a Text control for every second in the same format.
public class SliderTime extends Application {
@Override
public void start(Stage primaryStage) {
try {
HBox root = new HBox();
Scene scene = new Scene(root,400,400);
Slider sl = new Slider(0, 3600, 20);
sl.setMajorTickUnit(450);
sl.setShowTickLabels(true);
StringConverter<Double> stringConverter = new StringConverter<>() {
@Override
public String toString(Double object) {
long seconds = object.longValue();
long minutes = TimeUnit.SECONDS.toMinutes(seconds);
long remainingseconds = seconds - TimeUnit.MINUTES.toSeconds(minutes);
return String.format("%02d", minutes) + ":" + String.format("%02d", remainingseconds);
}
@Override
public Double fromString(String string) {
return null;
}
};
sl.setLabelFormatter(stringConverter);
Text text = new Text();
sl.valueProperty().addListener((observable, oldValue, newValue) ->
text.setText(stringConverter.toString(newValue.doubleValue())));
root.getChildren().addAll(sl, text);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
来源:https://stackoverflow.com/questions/37517949/how-can-i-set-the-javafx-slider-to-format-for-time