2017-02-19 36 views
0

我設法獲得2個按鈕使用if和else語句的工作。如果我添加另一個if/else語句,程序不再起作用。我怎樣才能添加更多的語句,使我的GUI中的其他按鈕工作?我有7個按鈕的代碼如何讓更多的按鈕做工用HandleButtonAction和if語句

package finalgui; 

import java.io.IOException; 
import java.net.URL; 
import java.util.ResourceBundle; 
import javafx.event.ActionEvent; 
import javafx.fxml.FXML; 
import javafx.fxml.FXMLLoader; 
import javafx.fxml.Initializable; 
import javafx.scene.control.Label; 
import javafx.scene.Parent; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.stage.Stage; 


public class FXMLDocumentController{ 

@FXML 
private Button btnViewSPC; 
@FXML 
private Button btnBack; 

@FXML 
private void handleButtonAction(ActionEvent event) throws IOException{ 
Stage stage; 
Parent root; 
if(event.getSource()==btnViewSPC) { 
    //get reference to the button's stage 
    stage=(Stage) btnViewSPC.getScene().getWindow(); 
    //load up next scene 
    root = FXMLLoader.load(getClass().getResource("addviewdel.fxml")); 
} 
else{ 
    stage=(Stage) btnBack.getScene().getWindow(); 
    root = FXMLLoader.load(getClass().getResource("FinalGUI.fxml")); 
} 
Scene scene = new Scene(root); 
stage.setScene(scene); 
stage.show(); 
} 

} 

回答

1

當然,你可以使用多個if語句destinguish多個按鈕

Object source = event.getSource(); 
if (source == button1) { 
    ... 
} else if (source == button2) { 
    ... 
} else if (source == button2) { 
    ... 
} 
... 
else { 
    ... 
} 

不過我個人更喜歡使用userData屬性的數據與Button關聯:

@FXML 
private void initialize() { 
    btnViewSPC.setUserData("addviewdel.fxml"); 
    btnViewSPC.setUserData("FinalGUI.fxml"); 
    ... 
} 

@FXML 
private void handleButtonAction(ActionEvent event) throws IOException { 
    Node source = (Node) event.getSource(); 

    Stage stage = (Stage) source.getScene().getWindow(); 
    Parent root = FXMLLoader.load(getClass().getResource(source.getUserData().toString())); 

    Scene scene = new Scene(root); 
    stage.setScene(scene); 
    stage.show(); 
} 

或者使用不同的方法來處理來自不同按鈕的事件。您還可以添加一個「助手法」來控制,以避免重複所有代碼:

@FXML 
private void handleButtonAction1(ActionEvent event) throws IOException { 
    showStage(event, "addviewdel.fxml"); 
} 

@FXML 
private void handleButtonAction2(ActionEvent event) throws IOException { 
    showStage(event, "FinalGUI.fxml"); 
} 

... 

private void showStage(ActionEvent event, String fxmlResource) throws IOException { 
    Node source = (Node) event.getSource(); 

    Stage stage = (Stage) source.getScene().getWindow(); 
    Parent root = FXMLLoader.load(getClass().getResource(fxmlResource)); 

    Scene scene = new Scene(root); 
    stage.setScene(scene); 
    stage.show(); 
}