Java和javafx的新手,我一直在编写一个gui,我一直在尝试找到一种方法在我的选项窗口中创建一个按钮,该按钮将更改所有窗口的背景颜色。我目前不确定该怎么做。
在主类中,我初始化以下字符串并使其成为全局字符串:
public static String background;
在选项类中,我有颜色选择器,然后将十六进制值转换为字符串
colorPicker.setLayoutX(15.0);
colorPicker.setLayoutY(184.0);
// 8 symbols.
String hex1 = Integer.toHexString(colorPicker.getValue().hashCode());
// With # prefix.
String hex2 = "#" + Integer.toHexString(colorPicker.getValue().hashCode());
// 6 symbols in capital letters.
String hex3 = Integer.toHexString(colorPicker.getValue().hashCode()).substring(0, 6).toUpperCase();
background.equals(hex1+hex2+hex3);
这行代码在每个类/窗口中用于更改背景颜色。
//sets background of current stage
backgroundpane.styleProperty().set("-fx-background-color: "+background);
但是,当我这样做时,我收到此错误:Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
指向background.equals(hex1+hex2+hex3);
任何帮助不胜感激
声明背景字符串时将其初始化为空字符串,以确保它永远不会为空。
public static String background = "";
也就是说,我认为您想将新背景分配给变量,而不是检查它是否已被选中。因此,如果这是正确的,您应该将background.equals(hex1+hex2+hex3);
替换为:
background = hex1+hex2+hex3;
您的十六进制字符串不完整,您需要 6 个十六进制字符,但由于您在前面加上"#"字符,因此您只能获得其中的 5 个字符。将子字符串调整为子字符串(0, 7(
此外,在第一次调用后,您不再需要调用colorpicker.getValue,因为它存储在hex1变量中。
确保正确更新主类静态背景属性,因此不要使用 background.equals(它只是将背景与某些东西进行比较,而不是分配值!(,而是使用 MainApp.background = hex3 (主应用程序是静态属性所在的任何地方(
还要确保静态背景值使用有效的十六进制字符串进行初始化。