对于GUI,我通过对每个“按钮”使用一个锚定板来制作类似于Spotify的最小化,最大化,关闭按钮。我通过scenebuilder创建了按钮,然后通过fxml将它们加载到类中。当鼠标进入或退出时,我无法弄清楚如何在控制器类中调用锚定窗格的特定实例来更改其背景颜色。
public static Stage primaryStage;
@Override
public void start(Stage primaryStage) throws Exception
{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setScene(new Scene(root, 1280, 800));
...
this.primaryStage = primaryStage;
etc.
是如何设置UI类的
我希望当鼠标进入边界时,锚定窗格的颜色会发生变化,但截至目前我还不知道如何调用它。
解决了这个问题,必须将一个fxid设置为anchorpane,然后在@FXML之后在控制器类中启动它。
有点像:
@FXML
Anchorpane someButton;
@FXML
public void makeButtonWhite(MouseEvent event)
{
someButton.setStyle("-fx-background-color: #ffffff");
}
执行此操作的最方便方法是使用样式表来分配背景。
<AnchorPane xmlns:fx="http://javafx.com/fxml/1" stylesheets="@style.css">
<children>
<AnchorPane prefWidth="30" prefHeight="20" styleClass="my-button"/>
</children>
</AnchorPane>
style.css(与fxml相同的目录)
/* default style */
.my-button {
-fx-background-color: blue;
}
/* style when mouse is inside the region */
.my-button:hover {
-fx-background-color: red;
}
这使您可以轻松地将样式添加到多个Region
s;你只需要添加它的样式类(styleClass="my-button"
)。
启动它所需的代码必须是起始类
public class Class extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(this.getClass().getResource("/Folder/File.fxml"));
loader.setController(yourControllerClass());
//only if you do something with the controller class afterwards
YourControllerClass controller = loader.setController();
Parent parent = loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(parent);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
你知道在scenebuilder中的代码方法你可以设置鼠标输入和退出按钮,标签等然后如果例如id为“closeButton”的按钮和OnMouseEntered“closeButtonOnEntered”和OnMouseExited“closeButtonOnExited”这将是你需要的代码
public yourcontrollerclass {
@FXML
Button closeButton;
@FXML
private void closeButtonOnEntered() {
//sets button red
button.setStyle("-fx-background-color: #ff0000");
}
@FXML
private void closeButtonOnExited() {
//sets button your first color
button.setStyle("-fx-background-color: transparent");
}
}
这几乎可以在sceneBuilder中完成
我希望我能帮助你(抱歉我的英语不好)