2016-12-29 81 views
0

我在AnchorPane中有10个圈子的FXML应用程序。我想将鼠标悬停在一个圆上,并使其他9和背景变暗。Javafx变暗背景

我能做的最好的是一些基本的FadeTransition,它只会让它们消失,不会变暗,再加上我不知道如何选择节点的所有子节点,除了一个有鼠标的节点。手动选择除一个以外的所有子项对于更多对象似乎并不真正有效

我试图谷歌它,但我只是找不到任何东西。 请发布一个链接到类似问题的线程或示例代码。任何帮助将非常感激。

+0

请参阅:[如何在JavaFX中实现节点选择](http://stackoverflow.com/a/40939611/1155209)(虽然这有点不同...)。 – jewelsea

+0

谢谢! :)) – Patrick

回答

2

您可以使用下面的示例。请注意,有一些假设,例如场景图中的每个节点都是一个Shape对象,并且每个形状都有一个与填充关联的Color对象。示例代码足以派生出与您的用例特别相关的其他解决方案。

import javafx.application.Application; 
import javafx.scene.Parent; 
import javafx.scene.Scene; 
import javafx.scene.layout.Pane; 
import javafx.scene.paint.Color; 
import javafx.scene.paint.Paint; 
import javafx.scene.shape.Circle; 
import javafx.scene.shape.Rectangle; 
import javafx.scene.shape.Shape; 
import javafx.stage.Stage; 

public class SelectionApp extends Application { 

    private Pane root = new Pane(); 

    private Parent createContent() { 

     root.setPrefSize(800, 600); 

     root.getChildren().add(new Rectangle(800, 600, Color.AQUA)); 

     for (int i = 0; i < 10; i++) { 
      Circle circle = new Circle(25, 25, 25, Color.GREEN); 

      // just place them randomly 
      circle.setTranslateX(Math.random() * 700); 
      circle.setTranslateY(Math.random() * 500); 

      circle.setOnMouseEntered(e -> select(circle)); 
      circle.setOnMouseExited(e -> deselect(circle)); 

      root.getChildren().add(circle); 
     } 

     return root; 
    } 

    private void select(Shape node) { 
     root.getChildren() 
       .stream() 
       .filter(n -> n != node) 
       .map(n -> (Shape) n) 
       .forEach(n -> n.setFill(darker(n.getFill()))); 
    } 

    private void deselect(Shape node) { 
     root.getChildren() 
       .stream() 
       .filter(n -> n != node) 
       .map(n -> (Shape) n) 
       .forEach(n -> n.setFill(brighter(n.getFill()))); 
    } 

    private Color darker(Paint c) { 
     return ((Color) c).darker().darker(); 
    } 

    private Color brighter(Paint c) { 
     return ((Color) c).brighter().brighter(); 
    } 

    @Override 
    public void start(Stage primaryStage) throws Exception { 
     Scene scene = new Scene(createContent()); 
     primaryStage.setTitle("Darken"); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

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

这是完美的!非常感谢! – Patrick