如何在javaFX

时间:2015-10-26 03:49:43

标签: class javafx colors javafx-2 pane

我有一些输入验证,我正在通过用户输入文本框的操作来完成。我希望它在输入字母时变为橙色,在输入数字时变为白色。我遇到的问题是,一旦应用程序意识到它是数字或字母,我就无法想到改变颜色的方法。

我需要它来获取用户的输入,查看TypedKey类然后查看if,否则if和基于该更改场景中的颜色。这是我能想到的最合理的方式,但如果有人知道更有效的方式,或者可以帮助我改进我认为的方式,那将非常感激。

@Override
public void start(Stage primaryStage) throws Exception {
    GridPane pane = new GridPane();
    pane.setHgap(5);
    pane.setVgap(5);
    pane.setAlignment(Pos.CENTER);

    Scene scene = new Scene(pane, 300, 200);
    pane.add(new Label("Salary and Wage"), 0, 0);
    pane.add(tfSalaryAndWage, 1, 0);
    pane.add(btOK, 1, 1);

    //Red color for tfSalary box
    Color redColor = Color.rgb( 255, 0 , 0, 0.5);
    BackgroundFill backgroundFill = new BackgroundFill(redColor, null, null);
    Background background= new Background(backgroundFill);
    tfSalaryAndWage.setBackground(background);


    TypedKey typedKeyHandler = new TypedKey(this);
    tfSalaryAndWage.setOnKeyTyped(typedKeyHandler);

    primaryStage.setScene(scene);
    primaryStage.setTitle("Loan Calculator");
    primaryStage.show();
}

输入验证类

class TypedKey implements EventHandler<KeyEvent> {
    ValidateDataTest formObj = null; // Declare a data member to represent an
                                        // object of the form class.

    Color blueBackgroundColor = null;

    public TypedKey(ValidateDataTest formObj) // This constructor receives an
                                                    // object of the form class.
    {
        this.formObj = formObj;
    }

    public void handle(KeyEvent e) {
        if ((e.getCharacter().compareTo("a") >= 0 && e.getCharacter()
                .compareTo("z") <= 0)
                || (e.getCharacter().compareTo("A") >= 0 && e.getCharacter()
                        .compareTo("Z") <= 0)) {
            System.out.println("LOOKS LIKE A Z WAS PRESSED");



        }

        else if ((e.getCharacter().compareTo("0") >= 0 && e.getCharacter()
                .compareTo("9") <= 0)) {
            System.out.println("LOOKS LIKE NUMBERS WERE PRESSED");

        }

    }
}

1 个答案:

答案 0 :(得分:1)

您的要求不需要单独的课程。

textProperty()

其中,textField.textProperty().addListener((ob, oldValue, newValue) -> { if (isNumeric(newValue)) { scene.setFill(Color.AQUA); } else { scene.setFill(Color.FIREBRICK); } }); 只是我写的私有方法。

isNumeric()

<强> MVCE

private boolean isNumeric(String str) {
    for(Character ch : str.toCharArray()){
        if(Character.isAlphabetic(ch)){
            return false;
        }
    }
    return true;
}