This question already has answers here:
compilation error: identifier expected

(4个答案)


在11个月前关闭。





我正在尝试使用setItems方法填充javafx应用程序TableView,
这样做时,我首先通过执行以下操作定义了控制器路径


fx:“ sample.Application”


然后,我用所有必需的构造函数,getter和setter的类名称“ Products”定义了数据模型。然后,我开始编写控制器代码,定义了所有必需的fx:具有FXML批注的id,我重写了显然没有任何错误的initialize方法,还填充了TableView我使用了ObserverList,并使用了observerArrayList称为Products的构造函数,在最后,当我尝试使用setItems()用fx:id =“ table”填充TableView时,出现错误:


table.setItems(prodList);


错误:


错误:(46、19)Java:预期的标识符
错误:(46、28)Java:预期的标识符


这是代码:


FXML代码:


<TableView fx:id="table" GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.halignment="LEFT" GridPane.rowIndex="3" >
        <columns>
            <TableColumn fx:id="col_id" text="PRODUCT ID"/>
            <TableColumn fx:id="col_name" text="NAME"/>
            <TableColumn fx:id="col_price" text="PRICE" />
            <TableColumn fx:id="col_tax" text="TAX" />
            <TableColumn fx:id="col_discount" text="DISCOUNT" />
        </columns>
</TableView>



控制器代码


public class Application implements Initializable {
    @FXML
    private TableView<Products> table;
    @FXML
    private TableColumn<Products, Integer> col_id;
    @FXML
    private TableColumn<Products, String> col_name;
    @FXML
    private TableColumn<Products, Integer> col_price;
    @FXML
    private TableColumn<Products, Integer> col_tax;
    @FXML
    private TableColumn<Products, Integer> col_discount;

    final ObservableList<Products> prodList = FXCollections.observableArrayList(
            new Products(11, "Laptop", 25000, 23, 12 )
    );


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        col_id.setCellValueFactory(new PropertyValueFactory<>("productId"));
        col_name.setCellValueFactory(new PropertyValueFactory<>("name"));
        col_price.setCellValueFactory(new PropertyValueFactory<>("price"));
        col_tax.setCellValueFactory(new PropertyValueFactory<>("tax"));
        col_discount.setCellValueFactory(new PropertyValueFactory<>("discount"));
    }

    table.setItems(prodList); //error
}

最佳答案

您尚未在initialize方法中设置属性值工厂。我认为这就是问题所在。

PropertyValueFactory<>中没有任何内容。您必须按照以下方式进行设置-

    col_id.setCellValueFactory(new PropertyValueFactory<Products, Integer>("productId"));
    col_name.setCellValueFactory(new PropertyValueFactory<Products, String>("name"));
    col_price.setCellValueFactory(new PropertyValueFactory<Products, Integer>("price"));
    col_tax.setCellValueFactory(new PropertyValueFactory<Products, Integer>("tax"));
    col_discount.setCellValueFactory(new PropertyValueFactory<Products, Integer>("discount"));


另一件事,table.setItems(prodList)应该在initialize方法内部。改正它。

07-26 09:27