![](/img/trans.png)
[英]how can I replace substring that occurs only once while excluding substring two or more times in a row?
[英]How i can bind two substring to one?
我有两个弦
private StringProperties firstName;
private StringProperties lastName;
private StringProperties nickName;
用户选择名字和姓氏,昵称是名字和姓氏的前3个字符的串联
我该怎么做?
实际上,我这样初始化它(这是整个类)。
public class Person {
private StringProperty firstName;
private StringProperty lastName;
private StringProperty nickName;
private ObservableList<Evento> eventi = FXCollections.observableArrayList();
public Person(String firstName, String lastName) {
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
if (firstName.length() > 2 && lastName.length() > 2)
this.nickName = new SimpleStringProperty(firstName.trim().substring(0,3).concat(lastName.trim().substring(0,3)));
else
this.nickName = new SimpleStringProperty("");
}
public ObservableList<Evento> getEventi() {
return eventi;
}
public String getFirstName() {
if(firstName == null) firstName = new SimpleStringProperty(this,"firstName");
return firstName.get();
}
public StringProperty firstNameProperty() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public String getLastName() {
if(lastName == null) lastName = new SimpleStringProperty(this, "lastName");
return lastName.get();
}
public StringProperty lastNameProperty() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
public String getNickName() {
if(nickName == null) nickName = new SimpleStringProperty(this,"nickName");
return nickName.get();
}
public StringProperty nickNameProperty() {
return nickName;
}
@Override
public String toString() {
return getNickName() + "(" + getLastName() + " " + getFirstName() + ")";
}
}
但是当我让用户更改名字或姓氏时,昵称不会更新。
您应该使用ReadOnlyStringProperty
作为昵称:
private ReadOnlyStringWrapper nickName= new ReadOnlyStringWrapper();
...
public final String getNickName() {
return nickName.get();
}
public final ReadOnlyStringProperty nickNameProperty() {
return nickName.getReadOnlyProperty();
}
至于绑定,您可以使用Bindings
类中的实用程序方法,也可以针对任何其他复杂情况实现自己的绑定。 本示例使用createStringBinding()
方法。 它具有Callable
功能接口(将用于计算新值)和可观察属性的列表(可观察到的值变化):
public Person(String firstName, String lastName) {
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
this.nickName.bind(Bindings.createStringBinding(()->{
if(this.firstName.get().length() > 2 && this.lastName.get().length() > 2) {
return this.firstName.get().substring(0,3).concat(this.lastName.get().trim().substring(0,3));
} else {
return "";
}
}, this.firstName, this.lastName));
}
您可以使用Bindings.format
:
nickName.bind(Bindings.format("%.3s%.3s", firstName, lastName));
%.3s
的3
是字符串的最大长度。
但是,这不会对字符串进行任何修剪(您可以在将字符串传递给firstName
和lastName
之前进行此修剪)。
它也适用于小于3个字符的字符串。 因此,您可以获得昵称,例如FoBar
, FooB
或Bar
(如果名字是一个空字符串)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.