样式类删除和添加按预期工作。我猜你的问题是 ToggleButton 没有被正确注入,它应该是:
@FXML private ToggleButton Button;
...
Button.getStyleClass().remove("defaultStyle");
Button.getStyleClass().add("newStyle");
在控制器类中。请注意“按钮”的大写 b,因为您已fx:id="Button"
在 FXML 文件中定义。另请注意,您不需要自己实例化ToggleButton Button
(like new ToggleButton()
)。
编辑:
这是更改样式类的代码示例。正如我所说,它按预期工作。把它和你的比较一下。
示例.fxml:
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="somepackage.SampleController">
<stylesheets>
<String fx:value="somepackage/style.css" />
</stylesheets>
<children>
<ToggleButton layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="mybutton" styleClass="defaultStyle" />
</children>
</AnchorPane>
SampleController.java:
package somepackage;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ToggleButton;
public class SampleController implements Initializable {
@FXML
private ToggleButton mybutton;
@FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("before :" + mybutton.getStyleClass());
mybutton.getStyleClass().remove("defaultStyle");
mybutton.getStyleClass().add("newStyle");
System.out.println("after :" + mybutton.getStyleClass());
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
MainDemo.java:
package somepackage;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class MainDemo extends Application {
@Override
public void start(Stage stage) throws Exception {
System.out.println("version: " + com.sun.javafx.runtime.VersionInfo.getRuntimeVersion());
Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
css 文件包含您的选择器。