How to restrict visibility of items?

烈酒焚心 提交于 2019-12-05 05:20:56

this is what the clip of a node is made for.

Example:

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;


public class ClipTest extends Application {

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

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

    Group root = new Group();

    StackPane pane = new StackPane();

    pane.setMaxWidth(100);
    pane.setMaxHeight(100);
    pane.setLayoutX(50);
    pane.setLayoutY(50);


    Rectangle rect = new Rectangle(100, 100);

    rect.setFill(null);
    rect.setStroke(Color.RED);

    Rectangle rect2 = new Rectangle(150, 150);

    rect2.setFill(Color.BLUE);

    pane.getChildren().addAll(rect2, rect);

    root.getChildren().add(pane);


//    Rectangle clip = new Rectangle(100, 100);
//    clip.setLayoutX(25);
//    clip.setLayoutY(25);
//    pane.setClip(clip);

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

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

This produces:

Uncommenting the lines regarding the clip produces:

You can use clipping functionality to achieve this.

public class ClipPane extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Pane clipPane = new Pane();
        clipPane.setStyle("-fx-border-color: red;");
        clipPane.setPrefSize(200, 200);

        Rectangle rect = new Rectangle(200, 200);
        clipPane.setClip(rect);

        Button btn = new Button("Hello, world!");
        btn.relocate(120, 0);
        clipPane.getChildren().add(btn);

        AnchorPane root = new AnchorPane();
        root.getChildren().add(clipPane);
        AnchorPane.setTopAnchor(clipPane, 50.);
        AnchorPane.setLeftAnchor(clipPane, 50.);

        stage.setScene(new Scene(root, 300, 300));
        stage.show();
    }

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

Another approach, with using of observables. To clip items outside pane bounds (like css oveflow:hidden):

// create rectangle with sizes of pane, 
// dont need to set x and y explictly 
// as positions of clip node are relative to parent node 
// (to pane in our case)
Rectangle clipRect = new Rectangle(pane.getWidth(), pane.getHeight());

// bind properties so height and width of rect 
// changes according pane's width and height
clipRect.heightProperty().bind(pane.heightProperty());
clipRect.widthProperty().bind(pane.widthProperty());

// set rect as clip rect
pane.setClip(clipRect);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!