2015-03-13 3 views
0

Я пытаюсь понять свойство прозрачности мыши. Это пример кода, состоит из 4 кнопки Я хочу, чтобы все кнопки кликабельным, но я не знаю, как ...JavaFX mouse transparent не работает

public class Example extends Application { 

public static void main(String[] args) { 
    Application.launch(args); 
} 

@Override 
public void start(Stage stage) throws Exception { 
    StackPane stackPane = new StackPane(); 

    ObservableList<Node> children = stackPane.getChildren(); 

    Button button = new Button("I'm not clickable"); 
    button.setMaxHeight(Double.MAX_VALUE); 
    button.setMaxWidth(Double.MAX_VALUE); 
    children.add(button); 

    VBox vbox = new VBox(); 
// vbox.setMouseTransparent(true); If i put this here, nothing work 
    vbox.setAlignment(Pos.CENTER); 
    vbox.setSpacing(20); 
    vbox.setPrefHeight(Double.MAX_VALUE); 
    vbox.setPrefWidth(400); 

    ObservableList<Node> vChildren = vbox.getChildren(); 
    vChildren.add(new Button("This")); 
    vChildren.add(new Button("Button")); 
    vChildren.add(new Button("Are clickable")); 

    BorderPane borderPane = new BorderPane(); 
// borderPane.setMouseTransparent(true); If i put this here, nothing work 
    borderPane.setLeft(vbox); 
    children.add(borderPane); 

    stage.setScene(new Scene(stackPane, 800, 600)); 
    stage.show(); 
} 
} 

Можете ли вы мне помочь?

+0

Если вы делаете прозрачную контейнерную мышь, ничего в контейнере (например, кнопки будут получать события мыши). Насколько я вижу, все работает так, как должно ... – jewelsea

+1

Можете ли вы объяснить, что вы пытаетесь сделать? Что вы подразумеваете под «clickable»? Что такое код (без вызовов 'setMouseTransparent (true)'), не делая того, что вы хотите сделать? –

ответ

1

Здесь вы идете, большая кнопка с тремя кнопками внутри. Но, как я уже сказал, это не имеет никакого смысла. Не от кодирования, не от юзабилити. Но если вам нужно, вы должны. Вот код:

public class Example extends Application { 

    public static void main(String[] args) { 
     Application.launch(args); 
    } 

    @Override 
    public void start(Stage stage) throws Exception { 

     StackPane stackPane = new StackPane(); 

     Button bigButton = new Button("I'm not clickable"); 
     bigButton.setOnAction(e -> System.out.println(e)); 
     bigButton.setMaxHeight(Double.MAX_VALUE); 
     bigButton.setMaxWidth(Double.MAX_VALUE); 
     stackPane.getChildren().add(bigButton); 

     VBox vbox = new VBox(); 
     vbox.setAlignment(Pos.CENTER); 
     vbox.setSpacing(20); 
     vbox.setPrefHeight(Double.MAX_VALUE); 
     vbox.setPrefWidth(400); 

     ObservableList<Node> vChildren = vbox.getChildren(); 
     Button button1 = new Button("This"); 
     button1.setOnAction(e -> { 
      System.out.println(e); 
      e.consume(); 
     }); 
     Button button2 = new Button("Button"); 
     button2.setOnAction(e -> { 
      System.out.println(e); 
      e.consume(); 
     }); 
     Button button3 = new Button("Are clickable"); 
     button3.setOnAction(e -> { 
      System.out.println(e); 
      e.consume(); 
     }); 

     vChildren.addAll(button1, button2, button3); 

     BorderPane borderPane = new BorderPane(); 
     borderPane.setCenter(vbox); 

     vbox.prefWidthProperty().bind(bigButton.widthProperty()); 
     vbox.prefHeightProperty().bind(bigButton.heightProperty()); 

     bigButton.setGraphic(borderPane); 

     stage.setScene(new Scene(stackPane, 800, 600)); 
     stage.show(); 
    } 
} 
1

Если вы установите прозрачность ящика узла на false, то он просто не получит событий мыши.

Я создал небольшой пример для вас, чтобы понять, что делает прозрачность мыши.

public class MouseTransparency extends Application { 

    @Override 
    public void start(Stage primaryStage) { 

     Group root = new Group(); 

     Rectangle outerRect = new Rectangle(100,100,200,200); 
     outerRect.setStroke(Color.BLUE); 
     outerRect.setFill(Color.BLUE.deriveColor(1, 1, 1, 0.2)); 

     Rectangle innerRect = new Rectangle(150,150,50,50); 
     innerRect.setStroke(Color.RED); 
     innerRect.setFill(Color.RED.deriveColor(1, 1, 1, 0.2)); 

     Circle circle = new Circle(250, 250, 50); 
     circle.setStroke(Color.GREEN); 
     circle.setFill(Color.GREEN.deriveColor(1, 1, 1, 0.2)); 

     // mouse transparency checkbox 
     CheckBox checkBox = new CheckBox("Enable Mouse Transparency"); 

     // bind inner rect mouse transparency to the checkbox value; in the end you'd rather use innerRect.setMouseTransparent(...); 
     innerRect.mouseTransparentProperty().bind(checkBox.selectedProperty()); 

     Label label = new Label("You clicked: "); 

     // add event handlers 
     outerRect.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> label.setText("You clicked: Outer Rectangle")); 
     innerRect.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> label.setText("You clicked: Inner Rectangle")); 
     circle.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> label.setText("You clicked: Circle")); 

     VBox vBox = new VBox(); 
     vBox.getChildren().addAll(checkBox, label); 

     root.getChildren().addAll(vBox, outerRect, innerRect, circle); 

     Scene scene = new Scene(root, 500, 500); 

     primaryStage.setScene(scene); 
     primaryStage.show(); 

    } 

    public static void main(String[] args) { 
     launch(args); 
    } 

} 

Если вы щелкнете по внутреннему прямоугольнику, когда прозрачность мыши не активна, он получит события. Если вы активируете прозрачность мыши для внутреннего прямоугольника, установив флажок, внешний прямоугольник получит события, когда вы нажмете на внутреннюю.

enter image description here

Однако следует скорее включить/отключить кнопки, если ваш предназначен случай использования кнопки.

+0

Итак, для моей проблемы нет решения? В swing я помню, что был setOpaque, и все отлично работает – Emax

+0

Пожалуйста, ответьте на вопрос в комментариях выше. В чем дело? – Roland

+0

У меня есть большая кнопка на корне этапа, на этом есть пограничная область, на пограничной панели слева есть vbox, в vbox есть 3 кнопки, как я могу заставить эту кнопку получать событие мыши? – Emax

Смежные вопросы