几天前,我设法使用JavaFX创建一个自定义按钮,创建一个简单的按钮并使用setStyle()
方法使用String
对象修改它的样式(其值取决于按钮是否有所不同)是否点击)作为参数。
我不知道如何将自定义按钮转换为class
每次我想要使用它时都可以导入,所以我一直在研究,我找到了this项目,其中包括使用Material Design定制的多个JavaFX控制器。我现在感兴趣的控制器是MaterialButton
,其源代码如下:
import com.sun.javafx.scene.control.skin.ButtonSkin;
import javafx.animation.Animation;
import javafx.animation.FadeTransition;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.ParallelTransition;
import javafx.animation.SequentialTransition;
import javafx.animation.Timeline;
import javafx.animation.Transition;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.scene.control.Button;
import javafx.scene.control.Skin;
import javafx.scene.control.SkinBase;
import javafx.scene.effect.BlurType;
import javafx.scene.effect.DropShadow;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.util.Duration;
@SuppressWarnings("restriction")
public class CustomButton extends Button {
private static final Duration RIPPLE_DURATION = Duration.millis(250); // Duration of the ripple effect
private static final Duration SHADOW_DURATION = Duration.millis(350); // Duration of the shadow effect
private static final Color RIPPLE_COLOR = Color.web("#FFF", 0.3); // Ripple color
public CustomButton() { // Except from the setPrefHeifht() method, everything between this braces seems useless.
// Probably I'm wrong, but why would you want to do this?
textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
if (!oldValue.endsWith(newValue.toUpperCase())) {
textProperty().set(newValue.toUpperCase());
}
});
setPrefHeight(36); // Height of the button
}
@Override
public Skin<?> createDefaultSkin() { // Overrides the default skin of the button.
ButtonSkin buttonSkin = (ButtonSkin) getSkin();
if (buttonSkin == null) {
buttonSkin = new ButtonSkin(this);
Circle circleRipple = new Circle(0.1, RIPPLE_COLOR); // Creates the circle that must appear when the
// ripple effect animation is displayed.
buttonSkin.getChildren().add(0, circleRipple); // Adds the nodes to the screen.
setSkin(buttonSkin);
createRippleEffect(circleRipple); // Creates the ripple effect animation.
getStyleClass().add("ripple-button"); // I don't know what this line does, but if it is
// removed, the button is narrowed.
}
return buttonSkin;
}
public ButtonSkin getButtonSkin() { // Returns the skin casted to a ButtonSkin.
return (ButtonSkin) getSkin();
}
public void setFlated(boolean flated) { // The button is "flated" when it's pressed, so I guess that this is the same that saying "clicked".
if (flated) {
getStyleClass().add("flat"); // I don't know what this does.
} else {
getStyleClass().remove("flat"); // I don't know what does this do, either.
}
}
public boolean getFlated() {
return getStyleClass().indexOf("flat") != -1; // If the style class doesn't contain "flat", it returns false.
}
public void toggled(boolean toggled) { // For as far as I know, a toggle is the switch from one effect to another.
if (toggled) {
getStyleClass().add("toggle"); // I know as much about this line as I know about the other "getStyleClass()" lines.
} else {
getStyleClass().remove("toggle"); // I know as much about this line as I know about the other "getStyleClass()" lines.
}
}
public boolean getToggled() {
return getStyleClass().indexOf("toggle") != -1; // If the style class doesn't contain "toggle". it returns false.
}
private void createRippleEffect(Circle circleRipple) { // Defines the ripple effect animation.
Rectangle rippleClip = new Rectangle(); // Creates a new Rectangle
rippleClip.widthProperty().bind(widthProperty()); // For as far as I understand, it binds the width property of the
// rippleClip to itself. Why would you do that?
rippleClip.heightProperty().bind(heightProperty()); // For as far as I understand, it binds the width property of the
// rippleClip to itself. Why would you do that?
circleRipple.setClip(rippleClip); // For as far as I know, clipping is the process that consists
// in hiding everything that is outside of a specified area.
// What this does is specifying that area so that the parts of the circle
// that are outside of the rectangle, can be hided.
circleRipple.setOpacity(0.0); // Sets the circle's opacity to 0.
/*Fade Transition*/
FadeTransition fadeTransition = new FadeTransition(RIPPLE_DURATION, circleRipple); // Creates the fadeTransition.
fadeTransition.setInterpolator(Interpolator.EASE_OUT);
fadeTransition.setFromValue(1.0);
fadeTransition.setToValue(0.0);
/*ScaleTransition*/
final Timeline scaleRippleTimeline = new Timeline(); // Creates the scaleRippleTimeLine Timeline.
DoubleBinding circleRippleRadius = new DoubleBinding() { // Binds the radius of the circle to a double value.
{
bind(heightProperty(), widthProperty());
}
@Override
protected double computeValue() {
return Math.max(heightProperty().get(), widthProperty().get() * 0.45); // Returns the greater of both.
}
};
// The below line adds a listener to circleRippleRadius.
circleRippleRadius.addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
KeyValue scaleValue = new KeyValue(circleRipple.radiusProperty(), newValue, Interpolator.EASE_OUT);
KeyFrame scaleFrame = new KeyFrame(RIPPLE_DURATION, scaleValue);
scaleRippleTimeline.getKeyFrames().add(scaleFrame);
});
/*ShadowTransition*/
Animation animation = new Transition() { // Creates and defines the animation Transition.
{
setCycleDuration(SHADOW_DURATION); // Sets the duration of "animation".
setInterpolator(Interpolator.EASE_OUT); // It sets the EASE_OUT interpolator,
// so that the shadow isn't displayed forever and its an animation.
}
@Override
protected void interpolate(double frac) {
setEffect(new DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, 0.30), 5 + (10 * frac), 0.10 + ((3 * frac) / 10), 0, 2 + (4 * frac)));
// Creates a a DropShadow effect and then sets it to "animation".
}
};
animation.setCycleCount(2);
animation.setAutoReverse(true);
final SequentialTransition rippleTransition = new SequentialTransition(); // Creates a SequentialTransition. The circle's scaling is the
// first transition to occur, and then the color of the button
// changes to the original one with fadeTransition
rippleTransition.getChildren().addAll(
scaleRippleTimeline,
fadeTransition
);
final ParallelTransition parallelTransition = new ParallelTransition();
getStyleClass().addListener((ListChangeListener.Change<? extends String> c) -> { // For as far as I understand, each time that the
// Style class changes, the lines of code between the
// braces are executed, but I still don't understand how
// does the Style class work.
if (c.getList().indexOf("flat") == -1 && c.getList().indexOf("toggle") == -1) {
setMinWidth(88);
setEffect(new DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, 0.30), 5, 0.10, 0, 2));
parallelTransition.getChildren().addAll(rippleTransition, animation);
} else {
parallelTransition.getChildren().addAll(rippleTransition);
setMinWidth(USE_COMPUTED_SIZE);
setEffect(null);
}
});
this.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> { // When the button is clicked, each object's value is assigned to the first
// that it must have at the beginning of the animation. Then, the animation
// starts.
parallelTransition.stop();
circleRipple.setOpacity(0.0);
circleRipple.setRadius(0.1);
circleRipple.setCenterX(event.getX());
circleRipple.setCenterY(event.getY());
parallelTransition.playFromStart();
});
}
public void setRippleColor(Color color) {
((Shape) ((SkinBase) getSkin()).getChildren().get(0)).setFill(color); // I don't understand this line of code.
}
}
由于我是JavaFX的新手,我将整个GitHub项目视为金矿,因为我不仅可以访问示例,了解如何创建自定义控制器作为可从其他人导入的类,它还展示了如何自定义其他几个控制器。
问题是有一些我不理解的代码行(如果您阅读我对源代码所做的评论,您将会这样做。)
例如,有几次使用getStyleClass().add("something")
。
我知道getStylesheets().add()
是如何运作的,但这是不同的;我会说“Style”类与CSS文件不同。
如果是这样的话,它是如何运作的?据我所知,用作String
方法参数的getStyleClass().add()
用于确定它是否位于带有if()
的“Style”类中声明以后;但是这个课究竟是什么?我没有在互联网上看到任何关于它的文件。
我在理解源代码末尾的setRippleColor()
方法时也遇到了问题。如果有人知道它是如何工作的,或者我应该注意什么来理解它,我会很感激。
提前致谢。
更新:有人指出ripple-button
是可以在GitHub项目中找到的CSS文件的一部分。
我复制了MaterialButton
类并将其粘贴到一个新项目中,因此只需提及它就无法访问ripple-button
。然而,事实证明,如果我删除这行代码,按钮会缩小。我可以用任何东西改变“波纹按钮”,结果将是相同的,但线必须在那里。为什么会这样?
更新2 :我已经了解了setRippleColor(Color color)
方法的作用:基本上它获取了圆形的皮肤并获取了它的子项,因此它可以在矩形的颜色变为矩形的颜色后更改一个Shape
。由于Rectangle
扩展Shape
,因此它会变成一个形状。实际上这很简单。
答案 0 :(得分:1)
有些问题可能会让你感到困惑。
首先,这些东西不是“控制器”而是“控制”,这只是为了清晰起见,因为它可能很容易混淆。
方法getStyleSheets()
返回ObservableList
类型String
。此列表包含定义应用程序样式的.css
文件的各种路径。样式添加在Scene
类型Parent
或Control
上。有关更多详细信息,请查看链接的JavaDoc或这些文章:
样式表定义控件的样式。它们还提供了一些可以在任何Node
到getStyleClass()
上设置的其他样式类,它们还返回类型为ObservableList
的{{1}},这次定义样式类名称。渲染名称时,在为String
定义的样式表集中查找,然后应用。如果没有找到这样的样式类,则会被忽略。 Node
是任何控件的基类。
方法Node
不会覆盖默认皮肤,正如您在评论中提到的那样,但是它定义了默认皮肤(嗯,部分正确,因为createDefaultSkin()
扩展CustomButton
Button
覆盖{1}}。一般来说,一个控件由一个'control'类和一个'skin'类组成,至少在JavaFX到版本8时就是这种情况,当它发生变化时。有关详细信息,请参阅the control architecture上的文章。