import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;
/**
* label,text,password
*/
public class Demo10 extends Application {
@Override
public void start(Stage stage) throws Exception {
Group group = new Group();
Scene scene = new Scene(group);
stage.setScene(scene);
stage.setTitle("javafx");
stage.setWidth(800);
stage.setHeight(800);
Label usernameLabel = new Label();
usernameLabel.setText("账号:");
usernameLabel.setLayoutX(50);
usernameLabel.setLayoutY(100);
// text
TextField username = new TextField();
// text.setText("这是文本");
username.setLayoutX(100);
username.setLayoutY(100);
// tip
Tooltip tip = new Tooltip("请输入7个字以内");
username.setTooltip(tip);
// placeholder
username.setPromptText("请输入7个字以内");
username.setFocusTraversable(false);
username.textProperty().addListener(validListener(username, 7));
Label passwordLabel = new Label();
passwordLabel.setText("密码:");
passwordLabel.setLayoutX(50);
passwordLabel.setLayoutY(140);
PasswordField password = new PasswordField();
password.textProperty().addListener(validListener(password, 7));
password.setLayoutX(100);
password.setLayoutY(140);
password.setPromptText("请输入7个字以内");
group.getChildren().addAll(usernameLabel, username, passwordLabel, password);
stage.show();
}
private ChangeListener validListener(TextInputControl text, int strLength) {
return (ChangeListener<String>) (observableValue, oldValue, newValue) -> {
if (newValue.length() > strLength) {
text.setText(oldValue);
}
};
}
}
08-21
1921
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)