处理JavaFX中的许多按钮

时间:2018-03-21 21:23:38

标签: button javafx switch-statement case handle

我们说我有一个JavaFX应用程序,想要在场景之间切换。每个场景都包含按钮,按下这些按钮会导致以下场景。

为了给我的按钮命令按下该怎么做,我尝试执行以下操作:

for (Button button : buttonsArray) //for each Button in ArrayList
    button.setOnAction( e -> handle(frameID, button.ID) ); 
    //give it the data about frame and button

问题是,handle方法包含大量的Switch-Case语句:

switch (frameID)  //lokking for a certain frame
{
    case 1: switch (ID)  // and a certain button
            {
             case 1: // lead to the certain scene 
             break;
            } break;
}

即使它使代码变得复杂,通过编写括号或break错误也很容易破坏所有内容。它也有点像垃圾代码。

那么,管理所有这些按钮的更好方法是什么?我对Java和OOP比较陌生,尽管我很乐意学习新东西。

2 个答案:

答案 0 :(得分:0)

为什么不从场景构建器添加按钮,然后为每个按钮添加一个动作

public void button1Action(ActionEvent event)
{do some work }

public void button2Action(ActionEvent event) { //do some work }

enter image description here

答案 1 :(得分:0)

尝试为每个按钮创建一个动作事件

public void PressButton(ActionEvent action){
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("YourFXML.fxml"));
            Parent root = (Parent) fxmlLoader.load();
            Stage stage = new Stage();
            stage.setScene(new Scene(root));
            stage.show();
}