Button a=new Button();
...
a.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent e)
{
Button []b=new Button();
...
}
});
After clicking the button a, the other buttons b will show up. I want to make an event handler for the buttons b. What should I do?
2 Answers 2
It's called adding a Node(button) dynamically. You can practice with this approach.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class JavaFXApplication91 extends Application
{
int idControl = 0;
@Override
public void start(Stage primaryStage)
{
VBox root = new VBox();
Button btn = new Button();
btn.setText("Add New Button");
btn.setId("Button " + idControl);
btn.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
idControl++;
Button tempButton = new Button();
tempButton.setText("Button " + idControl);
tempButton.setId("Button " + idControl);
tempButton.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event2)
{
System.out.println("You clicked: " + ((Button)event2.getSource()).getId());
}
});
root.getChildren().add(tempButton);
}
});
root.getChildren().add(btn);
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);
}
}
This app creates a button on start up. If you click the button it creates a new button. Each new button, when clicked, shows the id of the button being clicked.
Comments
You dont have to have a button handler inside a button handler, if the Button b shows up only after clicking Button a, you could add another Button b handler (outside Button a handler), Button b cannot not fire a click event if its not visible
Comments
Explore related questions
See similar questions with these tags.
Buttoninstance to aButton[]array, which the compiler will tell you in the message for the compilation error.