JavaFX TableView行已添加但不可见 [英] JavaFX TableView row added but not visible

查看:64
本文介绍了JavaFX TableView行已添加但不可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TableView,要用来自某些TextField的数据填充,为此,我复制了另一个自另一个TableView的代码,因为它一直在工作.但是在第二个TableView中,数据未在表中显示为行.我知道已添加数据,因为我可以使用键盘上的箭头键在各行之间切换,并且在调试器模式下,每次添加行时都会更新items属性.在另一个TableView中,代码可以正常工作,但在第二个上却无法正常工作,有关如何解决此问题的任何想法?我读了其他有关PropertyValueFactory的问题,但事实是,第一个示例有效,而第二个示例无效.我尝试更改变量的名称,但仍然看不到.

I have a TableView that I want to populate with data from some TextFields, to do this, I copied code from one other TableView I have in my aplication since it was working. But in this second TableView, the data is not being shown as rows in the table. I know the data was added because I can switch between the rows using the arrow keys on the keyboard, and in the debugger mode, the items property is updated every time I add the rows. In the other TableView the code is working properly but not on the second, any ideas on how to fix this? I read the other questions talking about the PropertyValueFactory, but the thing is, the first example works and the second one doesn't. I tried changing the name of the variables but still had no look.

存储数据的类:

public class Produto {
    private String nome, codigo;
    private double preco, precoCompra;
    private int quantidade;

    public String getNome(){return nome;}
    public String getCodigo(){return codigo;}
    public double getPreco(){return preco;}
    public int getQuantidade(){return quantidade;}
    public double getPrecoCompra(){return precoCompra;}

    public Produto (int quantidade, String nome) {
        this.quantidade = quantidade;
        this.nome = nome;
    }
    public Produto(String nome, String codigo, double preco, double precoCompra) {
        this.nome = nome;
        this.codigo = codigo;
        this.preco = preco;
        this.precoCompra = precoCompra;
    }
    public Produto(String nome, String codigo, double preco, double precoCompra, int quantidade) {
        this.nome = nome;
        this.codigo = codigo;
        this.preco = preco;
        this.precoCompra = precoCompra;
        this.quantidade = quantidade;
    }

    public Produto(String nome, int quantidade){
        this.nome = nome;
        this.quantidade = quantidade;
    }
}

TableView 1中的工作代码:

Working code from TableView 1:

控制器:

public class VerEstoque {
    @FXML
    BorderPane root;
    @FXML
    StackPane rootVE;

    @FXML
    private TableView tabela = new TableView();
    private TableColumn<Produto, String> codigo = new TableColumn<>("CODIGO");
    private TableColumn<Produto, String> nome = new TableColumn<>("NOME");
    private TableColumn<Produto, Double> preco = new TableColumn<>("PREÇO DE VENDA");
    private TableColumn<Produto, Double> precoCompra = new TableColumn<>("PREÇO DE COMPRA");
    private TableColumn<Produto, Integer> quantidade = new TableColumn<>("QUANTIDADE");

    private static ArrayList<Produto> produtos = new ArrayList<>();
    private static ObservableList<Produto> listaProdutos = FXCollections.observableArrayList();

    @FXML
    private void initialize() {
        Main.roots.add(rootVE);
        tabela.getColumns().addAll(codigo, nome, preco, precoCompra,  quantidade);
        codigo.setCellValueFactory(new PropertyValueFactory<>("codigo"));
        nome.setCellValueFactory(new PropertyValueFactory<>("nome"));
        preco.setCellValueFactory(new PropertyValueFactory<>("preco"));
        precoCompra.setCellValueFactory(new PropertyValueFactory<>("precoCompra"));
        quantidade.setCellValueFactory(new PropertyValueFactory<>("quantidade"));
        tabela.setItems(listaProdutos);
        tabela.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        buscarEstoque();
    }

    static void buscarEstoque() {
        //In this case the data is being pulled from a database and added to an arraylist
        BancoDeDados bd = BancoDeDados.getInstance();
        try {
            ResultSet rs = bd.select("SELECT * FROM Estoque");
            while (rs.next()) {
                produtos.add(new Produto(rs.getString("Nome"), rs.getString("Codigo"), rs.getDouble("PrecoVenda"), rs.getDouble("PrecoCompra") , rs.getInt("Quantidade")));
            }
            rs.close();
            listaProdutos.clear();
            listaProdutos.addAll(produtos);
            produtos.clear();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

FXML文件:

<StackPane xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:id="rootVE"
       prefHeight="400.0" prefWidth="600.0" fx:controller="mercado.controllers.VerEstoque">
<BorderPane prefHeight="400.0" prefWidth="600.0" fx:id="root">
    <top>
        <HBox alignment="CENTER">
            <children>
                <Label text="ESTOQUE" fx:id="titulo"/>
            </children>
        </HBox>
    </top>
    <center>
        <TableView fx:id="tabela"/>
    </center>
</BorderPane>

上面的代码按预期工作,但是下面的代码中有错误:

The above code works as intended but I have errors in the code below:

控制器:

public class DefinirProdutos {

    @FXML private StackPane rootDP;
    @FXML private VBox base;
    @FXML private TextField campoQtd, campoNome;
    @FXML private TableView tabela;
    private TableColumn<Produto, Integer> qtd = new TableColumn<>("Qtd");
    private TableColumn<Produto, String> nome = new TableColumn<>("Produto");
    private  ArrayList<Produto> arrayProdutos = new ArrayList<>();
    private  ObservableList<Produto> listaProdutos = FXCollections.observableArrayList();

    @FXML
    private void initialize() {
        tabela.getColumns().addAll(qtd, nome);
        tabela.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        campoNome.setPromptText("Produto");
        campoQtd.setPromptText("Qtd");
        nome.setCellValueFactory(new PropertyValueFactory<>("produto"));
        qtd.setCellValueFactory(new PropertyValueFactory<>("qtd"));
        tabela.setItems(listaProdutos);
     }

    @FXML
    private void adicionarProduto() {
        int valorQtd = campoQtd.getText().length();
        int valorNome = campoNome.getText().length();
        if(valorQtd == 0 && valorNome == 0){
            //warn that the textfields are empty, irrelevant
        }else if(valorQtd == 0){
            //warn that the textfield is empty
        }else if(valorNome == 0){
            //warn that the textfield is empty
        }else{
            //Codigo pra caso nao estiver adicionado na array
            arrayProdutos.add(new Produto(Integer.parseInt(campoQtd.getText()), campoNome.getText()));
            listaProdutos.clear();
            listaProdutos.addAll(arrayProdutos);
            tabela.refresh();
        }
    }
}

未显示的表格视图的FXML:

FXML for the tableview that does not show:

<StackPane xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" prefHeight="600.0" 
maxWidth="800.0" fx:id="rootDP"
fx:controller="mercado.controllers.DefinirProdutos">
    <VBox fx:id="base" spacing="30">
        <children>
            <HBox alignment="CENTER">
                <children>
                    <Label text="DEFINIR PRODUTOS" fx:id="titulo"/>
                </children>
            </HBox>
            <HBox alignment="CENTER" spacing="10">
                <children>
                    <TextField fx:id="campoQtd" alignment="CENTER"/>
                    <TextField alignment="CENTER" fx:id="campoNome"/>
                    <Button text="Adicionar" prefWidth="140" prefHeight="40" fx:id="btnAdd" 
onAction="#adicionarProduto"/>
                </children>
            </HBox>
            <TableView fx:id="tabela"/>
            <HBox alignment="CENTER" fx:id="confirmar">
                <children>
                    <Button text="Feito" prefWidth="200" prefHeight="40" fx:id="btnFeito"/>
                </children>
            </HBox>
        </children>
     </VBox>
 </StackPane>

推荐答案

反射通常是完成任务的最糟糕的方法,这就是原因之一.

Reflection is usually the worst possible way to accomplish a task, and this is one of the reasons.

使用反射时,编译器无法检查您是否为类,方法,字段或bean属性使用了错误或拼写错误的名称.在这种情况下,编译器无法检查您传递给PropertyValueFactory构造函数的参数是否有效.

When you use reflection, the compiler cannot check whether you’ve used an incorrect or misspelled name for a class, method, field, or bean property. In this case, the compiler cannot check whether the argument you pass to a PropertyValueFactory constructor is valid.

更好的方法是避免完全使用PropertyValueFactory,而是为每个TableColumn编写自己的单元格值工厂:

A better approach is to avoid using PropertyValueFactory entirely, and instead write your own cell value factory for each TableColumn:

codigo.setCellValueFactory(
    f -> new SimpleStringProperty(f.getValue().getCodigo()));
nome.setCellValueFactory(
    f -> new SimpleStringProperty(f.getValue().getNome()));
preco.setCellValueFactory(
    f -> new SimpleDoubleProperty(f.getValue().getPreco()));
precoCompra.setCellValueFactory(
    f -> new SimpleDoubleProperty(f.getValue().getPrecoCompra()));
quantidade.setCellValueFactory(
    f -> new SimpleIntegerProperty(f.getValue().getQuantidade()));

如果我们对DefinirProdutos类中的TableColumns做类似的更改:

If we make a similar change to your TableColumns in the DefinirProdutos class:

nome.setCellValueFactory(
    f -> new SimpleStringProperty(f.getValue().getProduto()));
qtd.setCellValueFactory(
    f -> new SimpleIntegerProperty(f.getValue().getQtd()));

编译器会帮助您通知那些方法不存在.

the compiler will helpfully inform you that those methods do not exist.

这篇关于JavaFX TableView行已添加但不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆