2016-03-07 43 views
0

我想創建一個命令列表,用於運行程序的ProcessBuilder,具體取決於在GUI上選擇的內容。如何使用切換按鈕建立字符串列表

我有10個按鈕,我需要每個按鈕來返回並添加一個字符串列表 當切換和刪除它,而沒有切換。

我正試圖將.isSelected添加到列表中,並在禁用時將其刪除。 但我認爲這不是一個好方法。

有沒有人有任何想法?

編輯:是否將所有按鈕添加到ToggleGroup並使用Switch是一個有效的解決方案?

+0

如果將所有按鈕添加到切換組中,一次只能選擇一個按鈕,這可能不是您想要的... –

回答

0

謝謝你們我去的是這樣的:

public ToggleButton getBuildBtn() { 

     final ToggleButton button = new ToggleButton("Build"); 

     button.setStyle("-fx-font: 15 verdana; -fx-base: " + buttonsColor + ";"); 
     button.setOnAction(event -> selectedhandler(button, "build")); 
     return button; 
} 

private void selectedhandler(final ToggleButton button, String command) { 
    if (button.isSelected()) { 
     button.setStyle("-fx-base: #00ff0f;"); 
     commands.add(command); 
    } else { 
     button.setStyle("-fx-base: " + buttonsColor + ";"); 
     commands.remove(command); 
    } 
} 

我會去想enumSet而重構。謝謝。

0

我會使用EnumSet。爲每個Button定義一個枚舉常量(帶有要顯示的名稱屬性),然後讓togglebutton添加或刪除集合中的枚舉。通過這種方式,按鈕類只需要具有作爲它的常量枚舉集的構造函數的參數。

通過迭代EnumSet,可以輕鬆地將參數添加到命令行中。

這個方案的好處是,Button類可以是小的和通用(增加一個命令行選項將只需添加一個new CommandOptionButton(Options.VERBOSE, optionsSet),而集比添加和從列表中刪除字符串算法好得多。

2

一個簡單的實現是:

public class MyApplication extends Application { 

    private final List<String> commands = new ArrayList<>(); 

    @Override 
    public void start(Stage primaryStage) { 
     VBox commandToggles = new VBox(); 
     commandToggles.getChildren().add(createCommandToggle("Command 1", "exec1")); 
     commandToggles.getChildren().add(createCommandToggle("Command 2", "exec2")); 
     commandToggles.getChildren().add(createCommandToggle("Command 3", "exec3")); 
     // ... 

     Button runButton = new Button("Run"); 
     runButton.setOnAction(e -> { 
      ProcessBuilder pb = new ProcessBuilder(commands); 
      // ... 
     }); 

     // ... 

    } 

    private ToggleButton createCommandToggle(String text, String executable) { 
     ToggleButton button = new ToggleButton(text); 
     button.selectedProperty().addListener((obs, wasSelected, isSelected) -> { 
      if (isSelected) { 
       commands.add(executable); 
      } else { 
       commands.remove(executable); 
      } 
     } 
     return button ; 
    } 
} 

由於@Valette_Renoux建議,可以通過封裝在enum按鈕的文本和可執行命令改進這一點,並用EnumSet替換名單這使得建築。切換按鈕的重複性稍差一些(儘管您可能需要在runButton處理程序中稍微多做一點工作才能提取命令)。