2017-02-19 38 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(); 
}