这个简单的应用程序与您展示的几乎相同:
package example;
import javafx.animation.Animation;
import javafx.animation.Transition;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Main extends Application {
public static void main(String[] args) {
launch(Main.class, args);
}
@Override
public void start(Stage stage) throws Exception {
final Pane root = new Pane();
// this color will be used for the Text-Color (not hovered), Border and the Background-Color (on hover)
final Paint color = Color.web("#B17461");
// basic stuff: text, font and text-color
final Label label = new Label("NEXT");
label.setFont(Font.font("Arial", 50.0));
label.setTextFill(color);
label.setTextAlignment(TextAlignment.CENTER);
// same padding as you had
label.setPadding(new Insets(15, 70, 15, 70));
// border with the same settings as you had (5px solid)
label.setBorder(new Border(new BorderStroke(color, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, new BorderWidths(5))));
// maybe there's a better way to do this, but this one is the one I know. Simple Transition-Animation with a cycle of .5s
// the interpolate-Method will be called by JavaFX on every frame with the current "progress" (from 0.0 to 1.0), so we simply calculate the background size in there
final Animation animation = new Transition() {
{
setCycleDuration(Duration.millis(500L));
}
@Override
protected void interpolate(double progress) {
final double total = label.getWidth() / 2.0;
final double current = (1.0 - progress) * total;
label.setBackground(new Background(new BackgroundFill(color, CornerRadii.EMPTY, new Insets(0.0, current, 0.0, current))));
}
};
// "hover": change text color and start the animation
label.setOnMouseEntered(event -> {
label.setTextFill(Color.web("#fff"));
animation.playFromStart();
});
// "unhover": stop animation, reset background and text color
label.setOnMouseExited(event -> {
animation.stop();
label.setBackground(null);
label.setTextFill(color);
});
root.getChildren().add(label);
stage.setScene(new Scene(root));
stage.sizeToScene();
stage.show();
}
}
基本上我只是在标签上以编程方式完成了您在 css 中的所有内容。
对于动画,我使用了一个简单的Transition 结合标签背景的Insets 值。 Insets 描述了背景不应该填充多少空间,它就像一个填充但仅用于背景。