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

3.5k views Asked by At

i have given right id in my fxml file but code does't work and no error too.i want to get input all in text and at add button pressed have to fill that data into tableview.Input is text,radio button and checkbox that convetred into string.and at selection of row have to delete that row on remove button click.

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","[email protected]","sadfdsf"),
                new Person("Isabella", "Johnson", "[email protected]","sdfsdaf"),
                new Person("Ethan", "Williams", "[email protected]","adsfdsf"),
                new Person("Emma", "Jones", "[email protected]","dsfsad"),
                new Person("Michael", "Brown", "[email protected]","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);
    }
}

}
2

There are 2 answers

2
varren On BEST ANSWER

You dont need to set cell factory on each click, can put all setCellValueFactory in 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")); 
} 

you also need to set NS every time in your handleAddButtonAction i think:

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

And the most importent part, i don't see where you are setting your data to the table: Add this in initialize table.setItems(data);

0
Sredny M Casanova On

this is an example, in Initialize method I have the setCellValueFactory, and I assign the items (an observable list) to the table trought the Mytable.setItems method:

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());
    }
}