gpt4 book ai didi

css - 在 JavaFX 8 中,我可以从字符串提供样式表吗?

转载 作者:技术小花猫 更新时间:2023-10-29 11:00:09 26 4
gpt4 key购买 nike

是否可以将整个样式表包裹在一个字符串中并应用于某个节点?用例是为 PseudoClass 添加特定的(不可更改的)行为。我知道我可以使用 pane.getStylesheets().add(getClass().getResource("mycss.css").toExternalForm());,但我想知道是否有某种方法可以直接嵌入源代码;沿线的东西:

pane.getStylesheets().add(
".button:ok { -fx-background-color: green; }\n"+
".button:ko { -fx-background-color: red; }");

最佳答案

我通过定义新的 URL 连接找到了一种方法:

private String css;

public void initialize() {
...
// to be done only once.
URL.setURLStreamHandlerFactory(new StringURLStreamHandlerFactory());
...
}

private void updateCss(Node node) {
// can be done multiple times.
css = createCSS();
node.getStylesheets().setAll("internal:"+System.nanoTime()+"stylesheet.css");
}

private class StringURLConnection extends URLConnection {
public StringURLConnection(URL url){
super(url);
}

@Override public void connect() throws IOException {}

@Override public InputStream getInputStream() throws IOException {
return new StringBufferInputStream(css);
}
}

private class StringURLStreamHandlerFactory implements URLStreamHandlerFactory {
URLStreamHandler streamHandler = new URLStreamHandler(){
@Override protected URLConnection openConnection(URL url) throws IOException {
if (url.toString().toLowerCase().endsWith(".css")) {
return new StringURLConnection(url);
}
throw new FileNotFoundException();
}
};
@Override public URLStreamHandler createURLStreamHandler(String protocol) {
if ("internal".equals(protocol)) {
return streamHandler;
}
return null;
}
}

显然协议(protocol)“内部”可以是任何(非冲突)格式正确的字符串,并且(在这个简单的例子中)文件路径被完全忽略。

我用它来设置全局 .css,所以我不需要记住多个字符串。似乎 Stream 只打开了一次,但我不知道这是否适用于所有情况。

请随意根据需要使代码复杂化;)

此方法归功于 Jasper Potts (see this example)

关于css - 在 JavaFX 8 中,我可以从字符串提供样式表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24704515/

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