2017-04-21 124 views
-1
Button a=new Button(); 
... 
a.setOnAction(new EventHandler<ActionEvent>() 
    { 
     public void handle(ActionEvent e) 
     { 
      Button []b=new Button(); 
     ... 
     } 
    });  

單擊按鈕a後,其他按鈕b將顯示出來。我想爲按鈕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。

0

您只需點擊Button a後不必須有一個按鈕,處理器內部的按鈕處理程序,如果Button b顯示出來,你可以添加另一個Button b處理器(外Button a處理程序),如果其不可見Button b無法不火click事件