package converter; import java.text.NumberFormat; import java.text.ParseException; import javafx.beans.InvalidationListener; import javafx.beans.property.DoubleProperty; import javafx.collections.ObservableList; import javafx.scene.control.ComboBox; import javafx.scene.control.Slider; import javafx.scene.control.TextField; import javafx.scene.control.TitledPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.util.StringConverter; public class ConversionPanel extends TitledPane { final static int MAX = 10000; private ComboBox<Unit> comboBox; private Slider slider; private TextField textField; private DoubleProperty meters; private NumberFormat numberFormat; private InvalidationListener fromMeters = t -> { if (!textField.isFocused()) { textField.setText(numberFormat.format(meters.get() / getMultiplier())); } }; private InvalidationListener toMeters = t -> { if (!textField.isFocused()) { return; } try { meters.set(numberFormat.parse(textField.getText()).doubleValue() * getMultiplier()); } catch (ParseException | Error | RuntimeException ignored) { } }; public ConversionPanel(String title, ObservableList<Unit> units, DoubleProperty meters) { setText(title); setCollapsible(false); numberFormat = NumberFormat.getNumberInstance(); numberFormat.setMaximumFractionDigits(2); textField = new TextField(); slider = new Slider(0, MAX, 0); comboBox = new ComboBox(units); comboBox.setConverter(new StringConverter<Unit>() { @Override public String toString(Unit t) { return t.description; } @Override public Unit fromString(String string) { throw new UnsupportedOperationException("Not supported yet."); } }); VBox vbox = new VBox(textField, slider); HBox hbox = new HBox(vbox, comboBox); setContent(hbox); this.meters = meters; comboBox.getSelectionModel().select(0); meters.addListener(fromMeters); comboBox.valueProperty().addListener(fromMeters); textField.textProperty().addListener(toMeters); fromMeters.invalidated(null); slider.valueProperty().bindBidirectional(meters); } /** * 返回当前选择的计量单位的乘数(单位/米)。 * @return */ public double getMultiplier() { return comboBox.getValue().multiplier; } }
JavaFX:互操作性