如何在stackpane中重新定位vbox

d6kp6zgx  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(389)

我希望垂直时间标记跟随鼠标在几个计时器上指示时间戳,但是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的中间:

qlckcl4x

qlckcl4x1#

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

@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));
   }
cbeh67ev

cbeh67ev2#

setmargin用一个小的演算来解决这个问题:

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

为什么需要这个微积分?

相关问题