首页 文章

JavaFX表列,SceneBuilder未填充

提问于
浏览
1

我一直在看教程,我似乎无法获得填充表格 . 我也在使用net beans和scenebuilder . 任何帮助将不胜感激!一直在挣扎5个小时 .

这是我的 Controller 类的代码:

public class FXMLDocumentController implements Initializable {

    @FXML
    private TableView<Table> table;
    @FXML
    private TableColumn<Table, String> countriesTab;

    /**
     * Initializes the controller class.
     */

    ObservableList<Table> data = FXCollections.observableArrayList(
            new Table("Canada"),
            new Table("U.S.A"),
            new Table("Mexico")
    );

    @Override
    public void initialize(URL url, ResourceBundle rb) {

        countriesTab.setCellValueFactory(new PropertyValueFactory<Table, String>("rCountry"));
        table.setItems(data);
    }
}

这是我的代码 Table

class Table {
    public final SimpleStringProperty rCountry;


    Table(String country){
        this.rCountry = new SimpleStringProperty(country);
    }

    private SimpleStringProperty getRCountry(){
        return this.rCountry;

    }
}

这是我的主要内容:

public class Assignment1 extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

1 回答

  • 2

    对于 PropertyValueFactory 来查找属性,项类(即本例中为 Table )需要 public 作为访问修饰符,而不是包私有 . 返回属性的方法也需要 public .

    此外,根据 PropertyValueFactory 工作所需的约定,返回属性本身的方法的正确名称是 <nameOfProperty>Property .

    此外,由于属性的实际类型是实现细节,因此使用 StringProperty 作为返回类型而不是 SimpleStringProperty 会更好 .

    public class Table {
    
        private final SimpleStringProperty rCountry;
    
        public Table(String country){
            this.rCountry = new SimpleStringProperty(country);
        }
    
        public StringProperty rCountryProperty() {
            return this.rCountry;
        }
    }
    

    如果您使用这些修饰符来阻止对属性的写访问,您仍然可以通过使用 ReadOnlyStringWrapper 并返回 ReadOnlyStringProperty 来实现此效果:

    public class Table {
    
        private final ReadOnlyStringWrapper rCountry;
    
        public Table(String country){
            this.rCountry = new ReadOnlyStringWrapper (country);
        }
    
        public ReadOnlyStringProperty rCountryProperty() {
            return this.rCountry.getReadOnlyProperty();
        }
    }
    

    如果根本没有对该属性的写访问权限,只需使用该属性的getter就足够了 . 在这种情况下,您根本不需要使用 StringProperty

    public class Table {
    
        private final String rCountry;
    
        public Table(String country){
            this.rCountry = country;
        }
    
        public String getRCountry() {
            return this.rCountry;
        }
    }
    

相关问题