JavaFX TitledPane删除鼠标悬停

时间:2019-05-16 16:22:32

标签: java javafx

我有此代码:

public static void main(String[] ar){

    launch(ar);

}

@Override
public void start(Stage primaryStage){

    TitledPane titledPane = new TitledPane("", null);
    titledPane.setCollapsible(false);
    titledPane.setContent(new javafx.scene.control.TextArea("George"));

    Platform.runLater(() -> {

        titledPane.lookup(".title").setStyle("-fx-background-color: rgba(255, 255, 255, 1);" +
                "-fx-border-style: solid;" +
                "-fx-border-color: rgba(0, 0, 0, 1);" +
                "-fx-border-width: 1px;");

        titledPane.lookup(".content").setStyle("-fx-background-color: rgba(255, 255, 255, 1);" +
                "-fx-border-style: solid;" +
                "-fx-border-color: rgba(0, 0, 0, 1);" +
                "-fx-border-width: 1px;");

    });

    HBox hBox = new HBox();
    hBox.setAlignment(Pos.CENTER);

    Text textTitle = new Text("CONSOLE");
    Button buttonClear = new Button("CLEAR");

    HBox.setMargin(textTitle, new Insets(0, 10, 0, 0));

    hBox.getChildren().addAll(textTitle, buttonClear);

    titledPane.setGraphic(hBox);

    primaryStage.setScene(new Scene(titledPane));
    primaryStage.show();

}

如果我将鼠标置于红线区域,则会触发按钮清除的鼠标悬停效果。

如果没有鼠标,如何停止触发按钮的鼠标悬停效果?

1 个答案:

答案 0 :(得分:2)

title悬停后,modena.css会更改一个named color's的值以使其具有悬停样式;具体来说,它会更改-fx-color。这似乎也具有将Button更改为其悬停样式的副作用。我希望这可以视为错误。

要解决此问题,请应用以下CSS(选择器假定Button是图形):

.titled-pane > .title:hover > .button {
    -fx-color: -fx-base;
}

.titled-pane > .title:hover > .button:hover {
    -fx-color: -fx-hover-base;
}

.titled-pane > .title:hover > .button:armed {
    -fx-color: -fx-pressed-base;
}

以上内容将使Button保持其默认样式。显然,您可以使用相同的选择器以自己的方式设置Button的样式。

由于您需要定位伪类,因此将CSS放在外部文件中会比使用setStyle内联设置样式更容易。为了保持外观,可以使用以下样式表(包括上述样式):

.titled-pane {
    -fx-collapsible: false;
    -fx-content-display: right;
    -fx-graphic-text-gap: 10px;
}

.titled-pane > .title,
.titled-pane > .content {
    -fx-background-color: white;
    -fx-border-style: solid;
    -fx-border-color: black;
    -fx-border-width: 1px;
}

.titled-pane > .title:hover > .button {
    -fx-color: -fx-base;
}

.titled-pane > .title:hover > .button:hover {
    -fx-color: -fx-hover-base;
}

.titled-pane > .title:hover > .button:armed {
    -fx-color: -fx-pressed-base;
}

这是使用此CSS的示例:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TitledPane;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        var pane = new TitledPane("CONSOLE", new TextArea("This is the console output."));
        pane.setGraphic(new Button("CLEAR"));

        var scene = new Scene(pane, 600, 400);
        scene.getStylesheets().add("Main.css"); // replace with your resource

        primaryStage.setScene(scene);
        primaryStage.show();
    }

}
相关问题