[英]JavaFX: How do you call and pass the control object?
这是一种获取不同 JavaFx 控件文本的方法。
private String getText(Node item) {
String txt = "";
if (item instanceof Label) {
if(!((Label)item).getText().isEmpty()){
txt = ((Label)item).getText();
}
}
if (item instanceof TextField) {
if(!((TextField)item).getText().isEmpty()){
txt = ((TextField)item).getText();
}
}
if (item instanceof CheckBox) {
if(!((CheckBox)item).getText().isEmpty()){
txt = ((CheckBox)item).getText();
}
}
return txt;
}
我正在尝试减少代码行。 而不是定义 Label、TextField、CheckBox 等。是否有一个对象类可以为所有其他控件调用并放在 Node 项旁边,以便我不需要重复和指定每个控件? 有没有办法让它像这样?
private String getText(Node item, X x) {
String txt = "";
if (item instanceof x) {
if(!((x)item).getText().isEmpty()){
txt = ((x)item).getText();
}
return txt;
}
我应该用什么代替 X & x。 我不知道我应该调用或替换 Control 什么对象。 只是不要在意 isEmpty 的逻辑。 我主要关心的是我应该调用或替换 Control 什么对象。 并像这样调用方法
getText(txtSample, TextField.class)
或者
getText(lblSample, Label.class)
谢谢你。
由于通用超类 Control 没有getText()
方法(因为并非所有控件都有文本),因此这是不可能的。
编辑:正如 James_D 指出的那样, Label
和CheckBox
确实有一个共同的祖先,它有方法getText()
,即Labeled
。 这为我们节省了另一个检查instanceof
。
但是,可以提取其余的相似性。 假设我们首先编写一个辅助方法来从控件中提取文本(注意与instanceof
相同的语句中的向下转换:
private String getRawText( final Node item )
{
if( item instanceof Labeled labeled )
return labeled.getText();
else if( item instanceof TextField field )
return field.getText();
else //this is the default
return "";
}
那么原来的函数就变成了:
private String getText( final Node item )
{
final var txt = getRawText( item );
return txt.isEmpty()
? ""
: txt;
}
但请注意,您检查text.isEmpty()
而默认值,您使用它初始化变量txt
本身为空( ""
)。 因此不需要检查空。 您的意思是.isBlank()
(仅去除空白字符串)? 还是getText() == null
?
否则,它可以被删除,然后你只剩下函数getRawText()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.