【问题标题】:How to perform multiple actions for a Button depending on ComboBox selection in JavaFX如何根据 JavaFX 中的 ComboBox 选择对 Button 执行多个操作
【发布时间】:2017-03-22 19:05:22
【问题描述】:

这是创建用户界面的主类:

public class Test extends Application {

@Override
public void start(Stage primaryStage) {

    FlowPane mainPane = new FlowPane();         


    FlowPane query = new FlowPane();            
    query.setPadding(new Insets(30,30,30,30));
    query.setHgap(10);
    query.setVgap(20);

    ComboBox<String> queryDropDown = new ComboBox<>();      
    queryDropDown.getItems().addAll("Gene", "Disease");
    queryDropDown.setValue("Select One");
    System.out.println(queryDropDown.getValue());


    query.getChildren().addAll(new Label("Select Category: "), queryDropDown);


    FlowPane userInput = new FlowPane();            
    userInput.setPadding(new Insets(30,30,30,30));
    userInput.setHgap(10);
    userInput.setVgap(20);

    TextField searchField = new TextField();    
    searchField.setPrefColumnCount(3);
    userInput.getChildren().addAll(new Label("Enter Query: "), new TextField());




    FlowPane searchButtonPane = new FlowPane();         

    searchButtonPane.setPadding(new Insets(30,30,30,200));
    searchButtonPane.setHgap(50);
    searchButtonPane.setVgap(50);
    Button searchButton = new Button("Search");

    searchButtonPane.getChildren().addAll(searchButton);

    ButtonHandlerClass handler1 = new ButtonHandlerClass();     
    searchButton.setOnAction(handler1);


    mainPane.getChildren().addAll(query, userInput, searchButtonPane);      

    Scene scene = new Scene(mainPane, 300, 250);
    primaryStage.setTitle("Genetic Database");
    primaryStage.setScene(scene);
    primaryStage.show();





}


public static void main(String[] args) {
    // Prints "Hello, World" to the terminal window.
    System.out.println("Hello, World");
    Application.launch(args);



}

}

这是按钮处理程序类

public class ButtonHandlerClass implements EventHandler<ActionEvent> {

@Override
public void handle(ActionEvent e) {
    System.out.println("Button Clicked");



}

}

我希望能够让相同的“搜索”按钮执行不同的操作,具体取决于用户在组合框中选择的选项。我尝试为组合框做类似于 ButtonHandlerClass 的事情。任何建议将不胜感激。

谢谢!

【问题讨论】:

  • 您希望 100% 创建 ButtonHandlerClass 或者您愿意接受其他解决方案?
  • 我是编程新手,所以任何你认为效果更好的替代解决方案都值得学习!
  • 通常在Swing Library 中的JavaFX 之前,使用实现MouseAdapter 的外部类是很常见的。

标签: java javafx actionevent


【解决方案1】:

way 1way 3 保留此事件处理程序:

           // Using an event handler
            EventHandler<ActionEvent> handler = new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent arg0) {
                    String selectedItem = queryDropDown.getSelectionModel().getSelectedItem();
                    System.out.println(selectedItem);
                    // ...code
                }
            };

方式 1

        //note that every time one action event handler is called
        //instead for multiple handlers you can use the way 3
        searchButton.setOnAction(handler);

方式 2(避免创建匿名类):

    //using lambda expression
    searchButton.setOnAction(a->{
        String selectedItem = queryDropDown.getSelectionModel().getSelectedItem();
        System.out.println(selectedItem);
        // ...code      
    });

方式 3:

你可以添加多个事件处理程序,所有的都会被调用)(例如你可以添加多个动作事件处理程序......

[这是way 1way 2无法做到的事情]:

    //adding an event handler
    searchButton.addEventHandler(ActionEvent.ACTION,handler);

    //or

    searchButton.addEventHandler(ActionEvent.ACTION,a->{
        String selectedItem = queryDropDown.getSelectionModel().getSelectedItem();
        System.out.println(selectedItem);
        // ...code      
    });

方式 4:

使用外部类(不推荐,除非你的代码太多以至于你不希望你当前的类有太多行);()

这里可能有不同的情况:

  • 该类将嵌套到您当前的类中?
  • ComboBox 是全局变量,可以从嵌套的 上课?
  • 如果 !2 那么你必须在构造函数上传递它的引用 外部类
  • 一百万种情况

    //情况3代码:

     public class ButtonHandlerClass implements EventHandler<ActionEvent> {
    
       ComboBox<String> comboBox;
    
       /**
       *Constructor
       */
       public ButtonHandlerClass(ComboBox comboBox){
    
         this.comboBox = comboBox;
    
      }
    
     @Override
      public void handle(ActionEvent e) {
         String selectedItem = queryDropDown.getSelectionModel().getSelectedItem();
                System.out.println(selectedItem);
                // ...code  
    
      }
    
     }
    
    }
    

【讨论】:

  • 这太棒了。我相信我了解您进入的所有 4 种方式,并且我也明白为什么不推荐外部课程。在同一个项目中使用多个类仍然是一个我很模糊的领域,所以我暂时尝试练习。我确实实现了所有 4 种方法,看看我是否能让它们工作,到目前为止一切都很好。感谢您的帮助!
  • @NSar 方式 4 不是很复杂的东西,你只需要熟悉 Java。要了解 static constuctors references,练习它们,你会是 ?。也是一个很好的lambdamethod reference 的知识适用于 Java 8 及更高版本。它将提高您的代码和性能!
  • 太棒了,我一定会去看看
【解决方案2】:

为什么不直接使用 switch 语句?

@Override
public void start(Stage primaryStage) {

    VBox vbox = new VBox();
    ComboBox<String> comboBox = new ComboBox();
    ObservableList<String> options = FXCollections.observableArrayList("one", "two", "three");
    comboBox.setItems(options);
    Button btn = new Button();
    btn.setText("Say 'Hello World'");
    btn.setOnAction((ActionEvent event) -> {
        if(comboBox.getValue() != null)
        {
            String tempString = comboBox.getSelectionModel().getSelectedItem();
            System.out.print(tempString);
            switch(tempString)
            {
                case "one":
                    btn.setText("one is selected in combobox");
                    break;
                case "two":
                    btn.setText("two is selected in combobox");
                    break;
                case "three":
                    btn.setText("three is selected in combobox");
                    break;
                default:
                    btn.setText("Nothing is selected in combobox");
            }
        }
    });

    StackPane root = new StackPane();
    vbox.getChildren().addAll(btn, comboBox);
    root.getChildren().addAll(vbox);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

【讨论】:

  • 我什至没有想过 switch 语句,这绝对是一个简单的方法来完成这个。对于以后的问题,我会记住这一点。谢谢!
猜你喜欢
  • 2018-05-30
  • 1970-01-01
  • 2014-08-10
  • 1970-01-01
  • 2013-01-19
  • 2017-10-26
  • 2019-03-15
  • 1970-01-01
  • 2017-08-20
相关资源
最近更新 更多