我正在尝试创建具有特定样式的 Button 类。
public class RoundBTN extends Button{
public RoundBTN(String name){
Button roundButton = new Button(name);
roundButton.setStyle("-fx-background-color: #20B2AA; -fx-background-radius: 15px; -fx-text-fill: #ffffff");
getChildren().add(roundButton);
}
}
然后当我进入我的应用程序类时尝试构建一个新按钮:
@Override
public void start(Stage stage) throws Exception {
StackPane layout = new StackPane();
layout.setPadding(new Insets(5));
layout.getChildren().add(new RoundBTN("test"));
stage.setScene(new Scene(layout,200,200));
stage.show();
}
当我运行程序时,我得到一个没有样式的空普通按钮。
很抱歉问这个菜鸟问题,但我无法让它工作。
答案 0 :(得分:2)
您正在类 Button
的构造函数中创建一个新的 RoundBTN
。这根本不会改变RoundBTN
。
在类 RoundBTN
的构造函数中你需要做的第一件事就是调用超类构造函数。然后您无需创建新的 Button
,而只需设置样式。
import javafx.scene.control.Button;
public class RoundBTN extends Button {
public RoundBTN(String name){
super(name);
setStyle("-fx-background-color: #20B2AA; -fx-background-radius: 15px; -fx-text-fill: #ffffff");
}
}
但如果您只想更改样式,则不需要扩展类 Button
,只需创建一个常规 Button
并设置其样式即可。
Button b = new Button("test");
b.setStyle("-fx-background-color: #20B2AA; -fx-background-radius: 15px; -fx-text-fill: #ffffff");