2015-06-26 26 views
1

我有兩個場景。第一個場景使用以下代碼調用第二個場景。Java FX從不同場景改變標籤的值

@FXML 
private void confirmation(ActionEvent event) throws IOException{ 
Stage confirmation_stage; 
Parent confirmation; 
confirmation_stage=new Stage(); 
confirmation=FXMLLoader.load(getClass().getResource("Confirmation.fxml")); 
confirmation_stage.setScene(new Scene(confirmation)); 
confirmation_stage.initOwner(generate_button.getScene().getWindow()); 
confirmation_stage.show(); 
} 

「Confirmation.fxml」中有一個名爲「Proceed」的標籤。

我需要從該函數中更改該標籤的內容並返回結果(true/false)。幫幫我?

回答

4

爲FXML創建一個ConfirmationController。從控制器中,公開一種方法,允許您傳遞數據(字符串)以設置爲標籤。

public class ConfirmationController implements Initializable { 

    ... 
    @FXML 
    private Label proceed; 
    ... 
    public void setTextToLabel (String text) { 
     proceed.setText(text); 
    } 
    ... 
} 

裏面你的方法,你正在加載的FXML,你可以有:

... 
FXMLLoader loader = new FXMLLoader(getClass().getResource("Confirmation.fxml")); 
confirmation = loader.load(); 
ConfirmationController controller = (ConfirmationController)loader.getController(); 
controller.setTextToLabel("Your Text"); // Call the method we wrote before 
... 
0

FXML中的標籤有一個setText方法。因此,對於你的情況下,「繼續」標籤看起來像:

Proceed.setText("The new text"); 

至於問題的第二部分,我不知道,以你所要求的100%。我真的沒有看到該函數返回true或false的任何情況。

0

假設你有一個名爲控制器:confirmation_controller.java'.該控制器裏面,你有一個公共的方法getProceedLabel()返回名爲Proceed標籤的參考。您可以嘗試以下代碼:

Stage confirmation_stage; 
Parent confirmation; 
confirmation_stage=new Stage(); 
FXMLLoader loader = new FXMLLoader(getClass().getResource("Confirmation.fxml")); 
confirmation = loader.load(); 
confirmation_controller controller = loader.getController(); 
Label label = controller.getProceedLabel(); 
label.setText("..."): 
confirmation_stage.setScene(new Scene(confirmation)); 
confirmation_stage.initOwner(generate_button.getScene().getWindow()); 
confirmation_stage.show(); 
+3

這是一個非常可怕的想法,雖然。從控制器暴露UI控件在每種可能的解釋下都會打破封裝。如果你打算在控制器類以外公開UI細節,首先分離視圖和邏輯(FXML和控制器類的基本點)是毫無意義的。應用程序應該共享* data *,而不是UI組件。 –

+0

是的你是對的。 – Kachna