【问题标题】:How to relocate a VBox inside a StackPane如何在 StackPane 中重新定位 VBox
【发布时间】:2021-03-11 12:36:51
【问题描述】:

我希望鼠标在几个计时码表上跟随一个垂直时间标记来指示时间戳,但 setLayoutX() 或 relocate() 对 StackPane 完全没有影响。

我写了以下最小可重现的例子:

public class VerticalTimeMarkIsNotRelocated extends Application {

   @FXML private StackPane timeMarkContainer;
   @FXML private Label     label;
   @FXML private VBox      timeMark;

   @FXML
   private void initialize() {
      StackPane.clearConstraints( timeMark );
      StackPane.setAlignment( label, Pos.BOTTOM_CENTER );
   }

   @FXML
   private void moveTimeMark( MouseEvent e ) {
      final double x = e.getX();
      System.err.printf( "%7.2f\n", x );
      timeMark.relocate( x, 0 );
   }

   @Override
   public void start( Stage primaryStage ) throws Exception {
      final Class<?> clazz = getClass();
      primaryStage.setScene( new Scene( FXMLLoader.load( clazz.getResource( clazz.getSimpleName() + ".fxml" ))));
      primaryStage.show();
   }

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

VerticalTimeMarkIsNotRelocated.fxml:

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

<?import java.net.URL?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.layout.VBox?>

<StackPane xmlns:fx="http://javafx.com/fxml" fx:controller="so.VerticalTimeMarkIsNotRelocated"
   fx:id="timeMarkContainer" prefWidth="420" prefHeight="140" onMouseMoved="#moveTimeMark">
   <stylesheets>
      <URL value="@VerticalTimeMarkIsNotRelocated.css" />
   </stylesheets>
   <Label fx:id="label" text="Replacement for several chronogram widgets" />
   <VBox  fx:id="timeMark" minWidth="1.0" maxWidth="1.0" />
</StackPane>

VerticalTimeMarkIsNotRelocated.css:

#timeMark {
  -fx-background-color: red;
}
#label {
  -fx-background-color: bisque;
  -fx-padding: 40px;
}

在下面的屏幕截图中,我们可以在 Eclipse 控制台中看到鼠标移动了,但垂直的红色标记仍然位于 StackPane 的中间:

【问题讨论】:

  • 基本上,您正在与布局作斗争(并通过误用边距来欺骗它做您想做的事情是..邪恶;) - 通过某些外部代码定位托管子级将被恢复每个布局传递。
  • 您似乎在扩展Application 的类中有Controller 代码。
  • @kleopatra:哪种布局更好用?

标签: java javafx layout


【解决方案1】:

以编程方式设置边距并使用 插图(双顶,双右,双底,双左)

   @FXML
   private void moveTimeMark( MouseEvent e ) {
      final double x = e.getX();
      System.err.printf( "%7.2f\n", x );
      StackPane.setMargin(timeMark, new Insets(0,x,0,0));
   }

【讨论】:

  • 不,它不能解决问题。运行它。
【解决方案2】:

setMargin 用一个小微积分解决问题:

@FXML
private void moveTimeMark( MouseEvent e ) {
   StackPane.setMargin( timeMark,
      new Insets( 0.0, 0.0, 0.0, -timeMarkContainer.getWidth()+2.0*e.getX()));
}

为什么需要这种微积分?

【讨论】:

    猜你喜欢
    • 2021-02-27
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多