2017-04-21 6 views
-1

ボタンaをクリックすると、他のボタンbが表示されます。私は、ボタンbのイベントハンドラを作成したい。私は何をすべきか?あなたはButton bだけButton aをクリックした後現れた場合、あなたはその表示されていない場合Button bは、クリックイベントを発生しませことができない、(Button aハンドラ外)別のButton bハンドラを追加することができ、ボタンのハンドラ内でボタンハンドラを持っている必要がいけないJavafx:ボタンハンドラのボタンハンドラ

+2

質問が分かりません。あなたが欲しいものを正確に行い、ボタンbのイベントハンドラを作成するだけで何が問題になっていますか? – Mark

+1

この問題はおそらく、 'Button'インスタンスを' Button [] '配列に代入しようとしたことによって発生しています。コンパイラはコンパイルエラーのメッセージをコンパイラから通知します。 – fabian

答えて

2

これはノード(ボタン)を動的に追加することです。この方法で練習することができます。

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

このアプリケーションは起動時にボタンを作成します。ボタンをクリックすると、新しいボタンが作成されます。クリックすると、クリックされたボタンのIDが表示されます。

関連する問題