如何在 table 视图中填充数据,用户在 javaFX 中单击按钮时输入

How to populate data in table view with user input on button click in javaFX

我已经在我的 fxml 文件中给出了正确的 id,但代码不起作用并且没有错误 too.i 想要以文本形式输入所有内容,并且在按下添加按钮时必须将该数据填充到 tableview.Input 是在选择行时转换为 string.and 的文本、单选按钮和复选框,必须在单击删除按钮时删除该行。

public class CashDrawerController implements Initializable 
{
   @FXML TextField UnitText;
   @FXML CheckBox NCCheck;
   @FXML TextField CurrencyText;
   @FXML  RadioButton BillRadio;
   @FXML RadioButton CoinRadio;
   String select="";
   String NC="N";
   @FXML TableView<Person> table;
   @FXML TableColumn<Person,String> unitcol ;
   @FXML TableColumn<Person,String> valuecol ;
   @FXML TableColumn<Person,String> typecol ;
   @FXML TableColumn<Person,String> nccol ;
  private finalObservableList<Person>data=FXCollections.observableArrayList(
                new Person("Jacob",  "Smith","jacob.smith@example.com","sadfdsf"),
                new Person("Isabella", "Johnson", "isabella.johnson@example.com","sdfsdaf"),
                new Person("Ethan", "Williams", "ethan.williams@example.com","adsfdsf"),
                new Person("Emma", "Jones", "emma.jones@example.com","dsfsad"),
                new Person("Michael", "Brown", "michael.brown@example.com","sdfsafd")
        );
@FXML
private void handleRemoveButtonAction(ActionEvent ev){

}
@FXML
private void  handleAddButtonAction(ActionEvent eve){
    if(BillRadio.isSelected()){
        select="Bill";
    }
    if(CoinRadio.isSelected()){
      select="Coin";
    }
    if(NCCheck.isSelected()){
        NC="Y";
    }        
   data.add(new Person(
            UnitText.getText(),
            CurrencyText.getText(),
            select,NC));
    UnitText.clear();
    CurrencyText.clear();
    Person obj=new Person("name1","val1","type","nc1");
    obj.setUnitName("name2");
    obj.setValue("val2");
    obj.setType("type2");
    obj.setNC("nc2");
unitcol.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<Person,String>("UnitName"));
  valuecol.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<Person,String>("Value"));


 typecol.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<Person,String>("Type"));



nccol.setCellValueFactory(newjavafx.scene.control.cell.PropertyValueFactory<Person,String>("NC"));  

}

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

}    


public static class Person {

    private final SimpleStringProperty UnitName;
    private final SimpleStringProperty Value;
    private final SimpleStringProperty Type;
     private final SimpleStringProperty NC;
    private Person(String uName, String val, String type,String nc) {
        this.UnitName = new SimpleStringProperty(uName);
        this.Value = new SimpleStringProperty(val);
        this.Type = new SimpleStringProperty(type);
        this.NC = new SimpleStringProperty(nc);
    }

    public String getUnitName() {
        return UnitName.get();
    }

    public void setUnitName(String uName) {
        UnitName.set(uName);
    }

    public String getValue() {
        return Value.get();
    }

    public void setValue(String val) {
        Value.set(val);
    }

    public String getType() {
        return Type.get();
    }

    public void setType(String type) {
        Type.set(type);
    }

    public String getNC(){
        return NC.get();
    }

    public void setNC(String nc){
        NC.set(nc);
    }
}

}

你不需要每次点击都设置cell factory,可以把所有setCellValueFactory放在initialize

public void initialize(URL url, ResourceBundle rb) { 
    unitcol.setCellValueFactory(new PropertyValueFactory<Person,String>("UnitName"));
    valuecol.setCellValueFactory(new PropertyValueFactory<Person,String>("Value"));
    typecol.setCellValueFactory(new PropertyValueFactory<Person,String>("Type"));
    nccol.setCellValueFactory(new PropertyValueFactory<Person,String>("NC")); 
} 

你还需要每次在 handleAddButtonAction 中设置 NS 我认为:

if(NCCheck.isSelected()) NC="Y";
else NS ="N"

最重要的部分,我没看到你在哪里设置你的数据到table:在initialize中添加这个table.setItems(data);

这是一个示例,在 Initialize 方法中我有 setCellValueFactory,并且我通过 Mytable.setItems 方法将项目(可观察列表)分配给 table:

package application.view;

import java.io.IOException;
import application.Main;
import application.model.ActoHabla;
import application.model.agent;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Text;
import javafx.util.StringConverter;

public class CommunicationModelController {
    private Main mainApp;
    private agent agente;
    @FXML
    private ProgressBar progreso;
    @FXML
    private TreeView<Object> arbol;
    @FXML
    private TextField nombre;
    @FXML
    private ComboBox<String> tipo;
    @FXML
    private ComboBox<agent> agentes_participantes;
    @FXML
    private TextArea objetivo;
    @FXML
    private TextArea datos_intercambiados;
    @FXML
    private TextArea precondicion;
    @FXML
    private TextArea terminacion;
    @FXML
    private TextArea descripcion;
    @FXML
    private TableView<ActoHabla> tabla_actos;
     @FXML
     private TableColumn<ActoHabla, String> NameColumn;
    @FXML
    private TableView<agent> tabla_agentes;
    @FXML
    private TableColumn<agent, String> AgenteColumn;

    @FXML
    TableColumn<Fila, String> clave;
    @FXML
    TableColumn<Fila, String> valor;
    @FXML
    private TableView<Fila> tabla= new TableView<>();
    private ObservableList<Fila> filas=FXCollections.observableArrayList();


    @FXML
    private void initialize() {
        NameColumn.setCellValueFactory(cellData -> cellData.getValue().getNombre());
        AgenteColumn.setCellValueFactory(cellData -> cellData.getValue().getName());

        ah=new ActoHabla();
        tabla_agentes.setItems(ah.getAgentes());
        iniciar_tabla();
        tabla_actos.getSelectionModel().selectedItemProperty().addListener(
                (observable, oldValue, newValue) -> ShowActoValues(newValue));

        agentes_participantes.setConverter(new StringConverter<agent>() {

            @Override
            public String toString(agent object) {
                return object.getNameString();
            }

            @Override
            public agent fromString(String string) {
                // TODO Auto-generated method stub
                return null;
            }
        });
    }


    public Main getMainApp() {
        return mainApp;
    }
    public void setMainApp(Main mainApp) {
        this.mainApp = mainApp;
        ObservableList<agent> a=FXCollections.observableArrayList();
        a.addAll(mainApp.getAgentData());
        agentes_participantes.setItems(a);
        tipo.setItems(mainApp.getDatabase().getActos_habla());
    }


    /**
     * Funcion que guarda un acto de habla en la lista correspondiente
     *
     * **/
    @FXML
    public void handleRegistrar(){
        ah.setNombre(new SimpleStringProperty(nombre.getText()));
        nombre.setText("");

        ah.setTipo(new SimpleStringProperty(tipo.getSelectionModel().getSelectedItem()));
        tipo.getSelectionModel().clearSelection();

        ah.setObjetivo(new SimpleStringProperty(objetivo.getText()));
        objetivo.setText("");

        ah.setDatosintercambiados(new SimpleStringProperty(datos_intercambiados.getText()));
        datos_intercambiados.setText("");

        ah.setPrecondicion(new SimpleStringProperty(precondicion.getText()));
        precondicion.setText("");

        ah.setCTerminacion(new SimpleStringProperty(terminacion.getText()));
        terminacion.setText("");

        ah.setDescripcion(new SimpleStringProperty(descripcion.getText()));
        descripcion.setText("");

        ObservableList<agent> a=FXCollections.observableArrayList();
        a.addAll(mainApp.getAgentData());

        agentes_participantes.setItems(a);

        boolean is=false;
        for (ActoHabla iter : agente.getModelo_comunicaciones().getActor()) {
            System.out.println(iter.getNombre()+" "+ah.getNombre());
            if(iter.getNombre().get().equals(ah.getNombre().get())){
                is=true;
                agente.getModelo_comunicaciones().getActor().removeAll(iter);
                agente.getModelo_comunicaciones().getActor().add(ah);
                break;
            }//hay uno igual
        }


        if(!is)
            agente.getModelo_comunicaciones().getActor().add(ah);

        ah=new ActoHabla();
        ObservableList<agent> ab=FXCollections.observableArrayList();
        ab.addAll(mainApp.getAgentData());
        agentes_participantes.setItems(ab);

        ah.getAgentes().removeAll();
        tabla_agentes.setItems(ah.getAgentes());
        mainApp.getMensaje().set("Acto de habla registrado!");
    }//

    @FXML
    public void handleAgregar(){
        ah.getAgentes().add(agentes_participantes.getSelectionModel().getSelectedItem());
        agentes_participantes.getItems().remove(agentes_participantes.getSelectionModel().getSelectedItem());
        agentes_participantes.getSelectionModel().clearSelection();
        mainApp.getMensaje().set("Agente agregado");
    }

    public void ShowActoValues(ActoHabla acto){
        //igualar acto con ah
        nombre.setText(acto.getNombre().get());
        ah.setNombre(acto.getNombre());

        tipo.getSelectionModel().select(acto.getTipo().get());
        ah.setTipo(acto.getTipo());

        objetivo.setText(acto.getObjetivo().get());
        ah.setObjetivo(acto.getObjetivo());

        ah.setAgentes(acto.getAgentes());
        tabla_agentes.setItems(ah.getAgentes());
        ObservableList<agent> temp=mainApp.getAgentData();
        temp.removeAll(acto.getAgentes());
        agentes_participantes.setItems(temp);


        ah.setDatosintercambiados(acto.getDatosintercambiados());
        datos_intercambiados.setText(acto.getDatosintercambiados().get());

        ah.setPrecondicion(acto.getPrecondicion());
        precondicion.setText(acto.getPrecondicion().get());

        terminacion.setText(acto.getCTerminacion().get());
        ah.setCTerminacion(acto.getCTerminacion());

        descripcion.setText(acto.getDescripcion().get());
        ah.setDescripcion(acto.getDescripcion());

    }

    public agent getAgente() {
        return agente;
    }

    public void setAgente(agent agente) {
        this.agente = agente;
        tabla_actos.setItems(agente.getModelo_comunicaciones().getActor());
    }
}