[英]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.