2016-12-13 14 views
1

我有一個非常簡單的問題。我搜索了javafx event頁面。可能是我忽略了一些細節。無論如何,如果你看我的代碼,一切工作正常。羣組鼠標事件未啓動Javafx

但是,如果我在一個組中包裝佈局並將其添加到場景而不是直接添加布局,佈局和contentPane似乎都停止檢測鼠標事件。事件該組,g,沒有得到鼠標事件。

這樣的行爲是否正常?爲什麼?

任何有關這個問題的幫助將不勝感激。

package mouseeventtest; 

import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.layout.BorderPane; 
import javafx.scene.layout.Pane; 
import javafx.scene.layout.StackPane; 
import javafx.scene.paint.Color; 
import javafx.stage.Stage; 


public class MouseEventTest extends Application { 
    BorderPane layout; 

    @Override 
    public void start(Stage primaryStage) { 
     primaryStage.setTitle("Test Mouse Event"); 

     layout = new BorderPane(); 
     Pane contentPane = new StackPane(); 
     layout.setCenter(contentPane); 

     layout.setOnMousePressed(e ->{ System.out.println("layout.setOnMousePressed..."); }); 
     contentPane.setOnMousePressed(e -> { System.out.println("contentPane.setOnMousePressed..."); }); 

     //Group g = new Group(layout); 
     //g.setOnMousePressed(e -> { System.out.println("g.setOnMousePressed ..."); }); 
     //Scene scene = new Scene(g, 800, 800, Color.WHITE); 
     Scene scene = new Scene(layout, 800, 800, Color.WHITE); 

     scene.setOnMousePressed(e -> { System.out.println("scene.setOnMousePressed..."); }); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
     primaryStage.show(); 
    } 

    /** 
     * @param args the command line arguments 
     */ 
    public static void main(String[] args) { 
     launch(args); 
    } 

} 
+0

它可能是一個錯誤? – Tania

回答

1

有(顯然)的方式Group S和Region s爲尺寸的差,當他們一場景的根。 A Group的大小足以容納其內容;而Region的大小適合整個場景。由於場景圖中基本沒有內容(除了某些容器​​),因此組的首選大小計算爲零。因此沒有什麼可以接收任何鼠標事件。

如果您在內容中添加了一些尺寸,例如

layout.setPrefSize(800, 800); 

然後您會看到組中的鼠標事件,如預期的那樣。

+0

詹姆斯你是男人! :)我是新的stackoverflow。我試圖將你的回答標記爲答案,但不知道如何。無論如何非常感謝你。應該讀更多。 javafx文檔中沒有提供這樣簡潔的解釋。謝謝! – Tania

+0

@Tania要標記答案是正確的,請點擊旁邊的複選標記。 –

+0

剛剛檢查過它。我也做了進一步的測試。 – Tania