在JavaFX-2中如何将一个不可调整大小的面板居中显示?

3
我正在尝试用JavaFX-2、FXML和Scene Builder创建一个简单的图像查看应用程序。这是我第一个JavaFX应用程序,我在处理面板和布局时遇到了麻烦。
基本上,我想要在我的应用程序的绝对中心以原始大小显示图片(无法缩放/调整大小)。另外,窗口应该是可调整大小的,因此如果图像比窗口的大小大,我想要有滚动条出现以便查看整个图像。
我试图创建的一个很好的例子是Adobe Photoshop布局:http://imgur.com/iLS0lum
这是我的当前布局:http://imgur.com/R7PJRVk。黑色Stack Pane表示图像。滚动条目前正常工作,但我找不到将Stack Pane置于中心的方法。
我觉得我缺少重要的东西,请问你能指点我正确的方向吗?
Thanks!
编辑:这是我的fxml代码:pastebin.com/CnxYEKF1
1个回答

2

你使用了AnchorPane作为ScrollPane的容器。如果你使用StackPane代替,它会默认将内容居中。然而,像其他任何Pane一样,StackPane会尽可能使用所有可用空间,因此它总是占据所有空间,从而无法居中。要解决这个问题,请将ScrollPane放在Group内。Group的大小始终与其子项一样大,并且可以通过设置ScrollPane的prefHeight和prefWidth来控制其宽度和高度。这是带有它的FXML(我为了简化示例删除了按钮的onClick侦听器):

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>

<?import javafx.scene.Group?>
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="700.0" prefWidth="700.0" xmlns:fx="http://javafx.com/fxml" fx:controller="test.StackOverflowController">
  <children>
    <VBox prefHeight="687.0" prefWidth="710.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
      <children>
        <ToolBar prefWidth="600.0" style="-fx-base: firebrick">
          <items>
            <Button fx:id="btn_ImgFromFile" mnemonicParsing="false" style="-fx-base: firebrick" text="Load Image From File" />
            <Button fx:id="btn_ImgFromWindow" mnemonicParsing="false" style="-fx-base: firebrick" text="Load Image From Window" />
            <Separator orientation="VERTICAL" prefHeight="21.0" />
            <Button fx:id="btn_LoadInfo" mnemonicParsing="false" style="-fx-base: firebrick" text="Load Window Info" />
            <Button fx:id="btn_SaveInfo" mnemonicParsing="false" style="-fx-base: firebrick" text="Save Window Info" />
          </items>
        </ToolBar>
        <StackPane fx:id="pane_main" prefHeight="200.0" prefWidth="200.0" VBox.vgrow="ALWAYS">
          <children>
            <Group>
            <ScrollPane fx:id="scroll_pane" prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="-1.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="1.0">
              <content>
                <StackPane fx:id="stack_pane" prefHeight="230.0" prefWidth="333.0" style="-fx-background-color: #000000;" />
              </content>
            </ScrollPane>
            </Group>
          </children>
        </StackPane>
      </children>
    </VBox>
  </children>
</AnchorPane>

Result:

enter image description here


非常感谢,正是我想要的!解释得非常完美! - sifrenette

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接