【问题标题】:Adding observableHashMap through fxml通过fxml添加observableHashMap
【发布时间】:2016-04-23 18:25:08
【问题描述】:

寻找直接在 fxml 中添加带有键->值对的observableHashMap 的语法。我要记录的哈希图是这个:

Map<String, int[][]> rules = new HashMap<>();

rules.put("34Life", new int[][] { { 3, 4 }, { 3, 4 } });
rules.put("Amoeba", new int[][] { { 1, 3, 5, 8 }, { 3, 5, 7 } });
rules.put("Assimilation", new int[][] { { 4, 5, 6, 7 }, { 3, 4, 5 } });

【问题讨论】:

  • 有可能做到这一点,但显然不是int[][]。如果您切换到自定义 Rule 类,会更容易。
  • 您可以直接在 FXML 中创建 ObservableMap&lt;String, List&lt;List&lt;Integer&gt;&gt;&gt;,但我看不到使用数组执行此操作的方法。无论如何,混合集合和数组并不是一个好主意(它与泛型的关系非常糟糕),正如@RANders00 已经指出的那样,无论如何为您的用例定义特定的类通常要好得多。

标签: java javafx collections fxml


【解决方案1】:

是的,这是可能的。

<?xml version="1.0" encoding="UTF-8"?>

<?import com.mycompany.myapp.ParentWithMap?>
<?import com.mycompany.myapp.Rule?>
<ParentWithMap xmlns:fx="http://javafx.com/fxml">
    <fx:define>
        <Rule fx:id="firstRule" someData="I am first"/>
        <Rule fx:id="secondRule" someData="This will be second"/>
        <Rule fx:id="thirdRule" someData="And this is the third"/>
    </fx:define>
    <rules firstRule="$firstRule" secondRule="$secondRule" thirdRule="$thirdRule"/>
</ParentWithMap>

对于这个例子,我创建了以下类:

package com.mycompany.myapp;

import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;
import javafx.scene.Parent;

public class ParentWithMap extends Parent {

    private ObservableMap<String, Rule> rules = FXCollections.observableHashMap();

    public ObservableMap<String, Rule> getRules() {
        return rules;
    }
}
package com.mycompany.myapp;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class Rule {

    StringProperty someData = new SimpleStringProperty(this, "someData");

    public String getSomeData() { return someData.get(); }
    public StringProperty someDataProperty() { return someData; }
    public void setSomeData(String someData) { this.someData.set(someData); }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Rule{");
        sb.append("someData=").append(getSomeData());
        sb.append('}');
        return sb.toString();
    }
}
package com.mycompany.myapp;

import javafx.fxml.FXMLLoader;

import java.io.IOException;

public class Sample {
    public static void main(String[] args) throws IOException {
        ParentWithMap parent = FXMLLoader.load(Sample.class.getResource("thefxml.fxml"));

        System.out.println(parent.getRules());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多