我第一次尝试使用JavaFX,我试图了解一下布局管理.我们如何访问控件的首选大小?
在下面的示例中,我尝试将最大宽度设置为大于首选宽度200像素.也就是说,我希望随着帧的宽度增加,按钮增长(最大).
但是,当我运行代码时,首选宽度为-1,因此将200添加到首选宽度时,最大宽度为199.
import javafx.application.Application;
import javafx.event.*;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.geometry.Insets;
public class BorderPaneSSCCE extends Application
{
@Override
public void start(Stage primaryStage)
{
Button button = new Button( "Button at PreferredSize" );
button.setMaxWidth( button.getPrefWidth() + 200 );
System.out.println(button.prefWidth(-1) + " : " + button.getPrefWidth());
button.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
System.out.println("Width: " + button.getWidth());
}
});
HBox root = new HBox();
HBox.setHgrow(button, Priority.ALWAYS);
root.getChildren().add(button);
Scene scene = new Scene(root);
primaryStage.setTitle("Java FX");
primaryStage.setScene(scene);
primaryStage.show();
System.out.println(button.prefWidth(-1) + " : " + button.getPrefWidth());
}
public static void main(String[] args)
{
launch(args);
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行代码并单击按钮时,我看到: Width: 139.0
调整框架的宽度后,按钮尽可能大,然后单击我看到的按钮: Width: 199.0
我希望看到Width: 339.0(即139 + 200)
那么,我们如何访问控件的首选大小/宽度?
getPrefWidth()USE_COMPUTED_SIZE默认情况下返回标志(即 -1)。
您可以使用prefWidth(-1)来获取内部计算的首选宽度。但是,在布局窗格(在您的示例中为 HBox)布置节点之前,不会计算首选宽度。这发生在第一次显示舞台时。
如果您希望最大宽度取决于首选宽度,您有多种选择。一种是在设置setPrefWidth()最大宽度之前将首选宽度设置为固定值。
另一种方法是在节点或布局窗格上实现自定义布局算法。这是使用自定义按钮的示例。
// button whose maxWidth is always prefWidth + 200
Button button = new Button() {
@Override
protected double computeMaxWidth(double height)
{
return this.prefWidth(height) + 200.0;
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3486 次 |
| 最近记录: |