gpt4 book ai didi

java - 如何向 JavaFX 2.2.6 中的 PopupControl 添加内容?

转载 作者:搜寻专家 更新时间:2023-11-01 03:08:17 24 4
gpt4 key购买 nike

我想实现一个简单的弹出控件,它应该可以用 CSS 设置样式。一切正常,唯一的问题是如何向其中添加内容(JavaFX 中的节点)?

PopupWindow.getContent() 方法在 JavaFX 2.2.6 中已弃用,并且无法使用 CSS,我可以看到内容,但 CSS 选择器将无法使用。

那么自己添加内容的最佳解决方案是什么?我应该为此目的实现自己的 Skin 类,还是有一种简单的方法让它发挥作用?

我准备了一个简单的用例:

import javafx.scene.control.Label;
import javafx.scene.control.PopupControl;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;

public class PopupTest extends PopupControl {
public PopupTest() {
getStyleClass().add("popup"); // not working!?

StackPane pane = new StackPane();
pane.getStyleClass().add("pane");
Rectangle rectangle = new Rectangle(250, 250);
rectangle.getStyleClass().add("rect");
Label text = new Label("popup test");
text.getStyleClass().add("text");
pane.getChildren().addAll(rectangle, text);

// how to display to pane when the popup is shown?
getContent().addAll(pane);
}
}

为了完整起见,这里是我的 MainApplication 和 CSS 文件:

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;

public class MainApplication extends Application {
@Override
public void start(Stage stage) throws Exception {
Group root = new Group();
final Scene scene = new Scene(root);
scene.getStylesheets().add(MainApplication.class.getResource("style.css").toExternalForm());

final Button button = new Button("show popup");
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
PopupTest popup = new PopupTest();
popup.show(scene.getWindow());

}
});
root.getChildren().add(button);

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

public static void main(String[] args) {
launch(args);
}
}

样式.css:

.popup {
-fx-font-size: 24px;
}

.popup .rect {
-fx-fill: green;
}

.popup .text {
-fx-text-fill: white;
-fx-font-weight: bold;
}

“.popup”选择器在这里不起作用,如果我将它设置为“ Pane ”,它将设置弹出窗口的样式,因此 css 是正确的:pane.getStyleClass().add("popup") ;//使用这个“修复”

最佳答案

这似乎可行:

getScene().setRoot(pane);

关于样式类不起作用:PopupControl 没有 getStylesheets() 方法。那么也许它只能通过 setStyle(...) 直接设置样式?您可以通过简单地设置 pane 样式或将 pane 包装在根 Pane 中并设置样式来解决这个问题。

关于java - 如何向 JavaFX 2.2.6 中的 PopupControl 添加内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15030249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com