Search code examples
javajavafxcomponentsjcomponentpane

How to only show a section of a JComponent/SwingNode/Java FX Pane


I'm building a Java FX music application and I have a Java FX Pane which contains a SwingNode which contains a JComponent and I want to be able to hide the top and bottom of this component and only show the middle section.

If I resize the Pane to be smaller than the Component then it displays just the top section of the Component, like this Top section of Component, but I would like a way to move the component upwards so that the middle section is visible and the top and bottom are cropped Middle section of Component

Anyone know a way to do this? TIA


Solution

  • If you want to clip the outer area simply, wrap the node to a Pane, set negative LayoutXY and suitable MaxSize. When the outer area overlaps the other Nodes, clipping may be required. For example:

    Pane viewPort = new Pane();
    viewPort.getChildren().add(yourSwingNode);
    
    // Top 200px and bottom 200px of yourSwingNode will be trimed.
    yourSwingNode.setLayoutY(-200.0);
    yourSwingNode.layoutBoundsProperty().addListener((o, ov, nv) -> {
        viewPort.setMaxHeight(nv.getHeight() - 400.0);
    });
    
    // Set a clip for the layout bounds of Pane if you need
    Rectangle clip = new Rectangle();
    viewPort.layoutBoundsProperty().addListener((o, ov, nv) -> {
        clip.setWidth(nv.getWidth());
        clip.setHeight(nv.getHeight());
    });
    viewPort.setClip(clip);