在Spinner Control中仅插入数字


问题内容

我在Java 8u40中测试了Spinner控件

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Spinner;
import javafx.scene.control.SpinnerValueFactory;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class MainApp extends Application
{
    public static void main(String[] args)
    {
        Application.launch(args);
    }

    @Override
    public void start(Stage stage)
    {
        final Spinner spinner = new Spinner();

        spinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 10000));
        spinner.setEditable(true);

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(10));

        int row = 0;

        grid.add(new Label("Spinner:"), 0, row);
        grid.add(spinner, 1, row);

        Scene scene = new Scene(grid, 350, 300);

        stage.setTitle("Hello Spinner");
        stage.setScene(scene);
        stage.show();
    }
}

我如何只能在微调器控制字段中插入数字?

现在,我可以插入数字和文本了。有没有可以作为例子的例子?


问题答案:

对该要求尚不完全确定-假设您要防止输入无法解析为有效Number的字符。

如果是这样,可以轻松使用Spinner编辑器中的TextFormatter:有了它,您将监视文本的任何更改并接受或拒绝。该决定封装在格式器的过滤器中。一个非常简单的版本(肯定还有更多事情要做,请参见Swing的DefaultFormatter)

// get a localized format for parsing
NumberFormat format = NumberFormat.getIntegerInstance();
UnaryOperator<TextFormatter.Change> filter = c -> {
    if (c.isContentChange()) {
        ParsePosition parsePosition = new ParsePosition(0);
        // NumberFormat evaluates the beginning of the text
        format.parse(c.getControlNewText(), parsePosition);
        if (parsePosition.getIndex() == 0 ||
                parsePosition.getIndex() < c.getControlNewText().length()) {
            // reject parsing the complete text failed
            return null;
        }
    }
    return c;
};
TextFormatter<Integer> priceFormatter = new TextFormatter<Integer>(
        new IntegerStringConverter(), 0, filter);

spinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(
        0, 10000, Integer.parseInt(INITAL_VALUE)));
spinner.setEditable(true);
spinner.getEditor().setTextFormatter(priceFormatter);