2017-09-23 4 views
1

아래 코드와 같이 기존 버튼을 클릭하여 새 버튼을 만들고 싶습니다. 이제 새로운 버튼이 현재 버튼과 동일한 기능을 갖기를 바랍니다. 새 버튼을 클릭하면 새 버튼도 생성됩니다. 원래 버튼에 더 많은 기능이 있고 새 버튼에도 이러한 기능이있을 수 있습니다. @fabian 제안에서현재 노드의 javafx 복사 기능을 다른 노드에

Button btn = new Button("Original Button"); 

    VBox root = new VBox(); 
    root.getChildren().add(btn); 

    btn.setOnMouseClicked(e->{ 
     root.getChildren().add(new Button("New button")); 
    }); 
+2

방법은 주위에, 예를 들어, 모든 단일 이벤트 핸들러를 복사하여이 일을하지 있습니다 'Button oldButton = (Button) e.getSource(); 버튼 newButton = 새 버튼 (...); newButton.setOnMouseClicked (oldButton.getOnMouseClicked());'. 그러나'addEventHandler'를 사용하여 추가 된 이벤트 핸들러는 열거 될 수 없습니다. 적어도 리플렉션을 통해 전용 멤버에 액세스하지 않아도됩니다. BTW : 일반적으로 onAction 이벤트는 onMouseClicked 대신 버튼에 사용됩니다. 이전 이벤트는 버튼에 포커스가있을 때 Enter 키를 누르면 트리거되기 때문입니다. – fabian

답변

1

코드 :

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.StackPane; 
import javafx.scene.layout.VBox; 
import javafx.stage.Stage; 

/** 
* 
* @author Sedrick 
*/ 
public class JavaFXApplication11 extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     VBox vbox = new VBox(); 

     Button btn = new Button(); 
     btn.setText("Say 'Hello World'"); 
     btn.setOnAction(new EventHandler<ActionEvent>() { 

      @Override 
      public void handle(ActionEvent event) { 
       Button oldButton = (Button)event.getSource();     
       Button newButton = new Button("new Button"); 
       vbox.getChildren().add(newButton); 
       newButton.setOnAction(oldButton.getOnAction());    
      } 
     }); 


     vbox.getChildren().add(btn); 

     StackPane root = new StackPane(); 
     root.getChildren().add(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); 
    } 

} 
관련 문제