4

This is the main class to create the user interface:

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);



}

}

This is the button handler class

public class ButtonHandlerClass implements EventHandler<ActionEvent> {

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



}

}

I want to be able to have the same "search" button perform a different action depending on the option that the user chose in the combo box. I've tried doing something similar to the ButtonHandlerClass for the combo box. Any advice would be appreciated.

Thanks!

Danh
  • 5,916
  • 7
  • 30
  • 45
NSar
  • 41
  • 5
  • You want 100% to create the `ButtonHandlerClass` or you are opened to other solutions? – GOXR3PLUS Nov 09 '16 at 02:29
  • I'm new to programming so any alternative solutions that you think would work better would be awesome to learn about! – NSar Nov 10 '16 at 00:46
  • Generally before `JavaFX` in `Swing Library` it was very common to use an external class which implements `MouseAdapter`. – GOXR3PLUS Nov 10 '16 at 00:47

2 Answers2

4

Keep this event handler for way 1 and way 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
                }
            };

Way 1:

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

Way 2(avoid creating anonymous classes):

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

Way 3:

(you can add multiple event handler and all will be called)(for example you can add multiple action event handlers...)

[That is something you can not do with way 1 and way 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      
    });

Way 4:

Using an external class(not recommended , except if you have so much code that you don't want your current class to be too much lines) ;( )

Here can be different situations :

  • The class will be nested to your current class?
  • The ComboBox is global variable and can be accessed from the nested class?
  • If !2 then you have to pass a reference of it on the constructor of the External class
  • There is one million situations

    //Situation 3 code:

     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  
    
      }
    
     }
    
    }
    
GOXR3PLUS
  • 6,877
  • 9
  • 44
  • 93
  • This is fantastic. I believe I understand all 4 ways you went into and I also get why an external class would not be recommended. Using multiple classes for the same project is still an area I'm blurry on so I'm trying to practice that for the time being. I did implement all 4 ways to see if I could get them to work and so far so good. Thank you for the help! – NSar Nov 10 '16 at 01:01
  • 1
    @NSar the way 4 is not something very complex,you just need to know Java good.To understand `static` `constuctors` `references`,practice them and you will be .Also a good knowledge of `lambda` and `method reference` is appropriate for Java 8 and above.It will improve your code and performance ! – GOXR3PLUS Nov 10 '16 at 01:22
  • 1
    Awesome, I'll be sure to check those out – NSar Nov 10 '16 at 01:27
2

Why not just use a switch statment?

@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);
}
SedJ601
  • 12,173
  • 3
  • 41
  • 59
  • 1
    I didn't even think about a switch statement, definitely an easy way to accomplish this. I'll keep this in mind for future issues. Thanks! – NSar Nov 10 '16 at 01:02