2017-10-10 81 views
0

我想让JavaFX MediaView拉伸以填充父容器。如何使JavaFX MediaView拉伸媒体填充父项?

我试图从谷歌的一些方法之前,但没有帮助的(也许我是不适用是正确的),并有同名的这个问题,但这个问题的解决方案也许不适合我。

首先我用ahchorpane锚mediaview却发现它不能mediaview舒展了,我不知道为什么,因为像按钮其他控件可以工作。

然后我尝试它的宽度和高度结合anchorpane(mediaview的母公司)

Region region=(Region) mediaplayer.getParent(); 
    mediaplayer.setPreserveRatio(false); 
    mediaplayer.fitWidthProperty().bind(region.widthProperty()); 
    mediaplayer.fitHeightProperty().bind(region.heightProperty()); 

它可以扩大mediaview什么时候我调整窗口,但不能缩小下来! 我想这可能是因为区域的大小取决于它的孩子?

最后,我尝试绑定mediaview'size到stage'size,它的工作,但代码看起来很丑,因为我需要计算尺寸manully。

mediaplayer.setPreserveRatio(false); 
    mediaplayer.fitWidthProperty().bind(stage.widthProperty().subtract(200)); 
    mediaplayer.fitHeightProperty().bind(stage.heightProperty().subtract(135)); 

有没有更好的解决方案?

+0

不要使用AnchorPane了点。将您的MediaView放在BorderPane的中心。 – VGR

回答

1

使用下面你的代码会看到,你是能够伸展并不亚于你喜欢缩小mediaView(取决于舞台尺寸的)

import java.io.File; 
import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.layout.BorderPane; 
import javafx.scene.media.Media; 
import javafx.scene.media.MediaPlayer; 
import javafx.scene.media.MediaView; 
import javafx.stage.FileChooser; 
import javafx.stage.Stage; 

public class TestApp extends Application { 

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

    @Override 
    public void start(Stage stage) { 

     BorderPane pane = new BorderPane(); 

     FileChooser fc = new FileChooser(); 
     File mediaFile = fc.showOpenDialog(null); 

     MediaView moviePlayer; 

     if (mediaFile != null) { 
      MediaPlayer player = new MediaPlayer(new Media(mediaFile.toURI().toString())); 

      moviePlayer = new MediaView(player); 

      moviePlayer.setPreserveRatio(false); 
      moviePlayer.fitWidthProperty().bind(pane.widthProperty()); 
      moviePlayer.fitHeightProperty().bind(pane.heightProperty()); 

      pane.getChildren().add(moviePlayer); 
      player.play(); 

     } 

     Scene scene = new Scene(pane, 300, 300); 
     stage.setScene(scene); 
     stage.show(); 
    } 
} 

该代码可以使用AnchorPane以及所以我想如果您的问题仍然存在,或者我不了解您的需求,那么代码还有其他问题。制作一个简单的可运行程序来演示该问题。

+0

它的工作好,和一些测试后,我发现我的错误是不是这个原因引起的,谢谢 – BlackCat

0

尝试添加该动作监听用于重新调整大小:

MediaView.getParent().layoutBoundsProperty().addListener(new ChangeListener<Bounds>() { 
     @Override 
     public void changed(ObservableValue<? extends Bounds> observable, Bounds oldValue, Bounds newValue) { 
      mediaView.setFitHeight(newValue.getHeight()); 
      mediaView.setFitWidth(newValue.getWidth()); 
     } 
    }); 

这应该叫每个父尺寸得到了改变或最大化,然后在视图应该被调整到父,太费时间。

+0

我尝试,并找到它可以扩大,但不能缩小。 – BlackCat

+0

当我展开窗口时,anchorpane的宽度变大了,但是当我尝试缩小窗口时,anchorpane的宽度不会改变。 – BlackCat

+0

我很抱歉 - 您需要尝试一些更改。我现在很忙,所以也许其他人有一些空间来帮助:) 只想说 - 不要等我。 – LenglBoy