Редактировать столбец с помощью текстового поля и кнопку обновления с помощью JavaFX - PullRequest
0 голосов
/ 05 апреля 2020

Я пытаюсь редактировать столбцы с помощью кнопки обновления при вводе данных в текстовое поле. Я использую JavaFX для этого. Я до сих пор был в состоянии добавить и удалить столбец, но не могу редактировать их. Я не использую базу данных, просто использую документ .txt для выполнения этой операции CRUD. В настоящее время я могу изменить только текст в текстовом поле «updateName» на выбранный столбец, вместо того чтобы изменить выбранный столбец на текст, введенный в текстовое поле.

package javafxapplication4.businesslogic;

import java .io.Serializable;

publi c Класс FoodItem реализует Serializable {

private int ID;
private String name;
private float price;



public String getName() {
    return name;
}

public void setID(int ID) {
    if (this.ID==0) {
        this.ID = ID;
    }
}

public int getID() {
    return ID;
}
public void setName(String name) {
    if (!name.equals("")) {
        this.name = name;
    }
}

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    if (price > 0.0) {
        this.price = price;
    }
}

public FoodItem() {
    name = "UNALLOCATED";
    price = -1.0F;
}

public FoodItem(int ID, String name, float price) {

    //No blank items
    if (price > 0.0 && !name.equals("")) {
        this.ID = ID;
        this.name = name;
        this.price = price;
    }
}

@Override
public String toString() {
    return "FoodItem{ ID=" + ID + ", name=" + name + ", price=" + price + '}';
}

}

пакет javafxapplication4.ui;

publi c класс JavaFXApplication4 расширяет приложение {

private FoodItemAdapter fia;

@Override
public void start(Stage primaryStage) {


    fia = new FoodItemAdapter(new FoodItemPersistenceLayer());
    //Set up a list of food items
    List<FoodItem> myFoodItems = fia.readAllFoodItems();

    //Declare controls and event handlers
    TextField tfName = new TextField();
    TextField tfPrice = new TextField();
    Button btnAddFoodItem = new Button();
    Button btnDeleteFoodItem = new Button();
    Button btnUpdateFoodItem = new Button();
             TextField updateName = new TextField(); 
              TextField updatePrice = new TextField(); 
    TableView<FoodItem> table = new TableView<>();


    //Set up data for ComboBox. We don't care about how this data is
    //populated, but this is not a very good way of doing things.
    final ObservableList<String> options = FXCollections.observableArrayList();
    for (FoodItem f : myFoodItems) {
        options.add(f.getName());
    }



    final ObservableList<FoodItem> tableData = FXCollections.observableArrayList(myFoodItems);


    ComboBox comboBox = new ComboBox(options);

    btnAddFoodItem.setText("Add");
    btnDeleteFoodItem.setText("Delete");
    btnUpdateFoodItem.setText("Update");

    btnAddFoodItem.setOnAction(event -> {
                                            String name = tfName.getText();
                                            float price = Float.parseFloat(tfPrice.getText());
                                            FoodItem f = fia.createFoodItem(name, price);
                                            myFoodItems.add(f);
                                            options.add(f.getName());
                                            tableData.add(f);
                                            tfName.setText("");
                                            tfPrice.setText("");
                                        });

     btnDeleteFoodItem.setOnAction(event -> {
                                       FoodItem selectedItem = table.getSelectionModel().getSelectedItem();
                                       table.getItems().remove(selectedItem);
                                       fia.deleteFoodItem(selectedItem);
                                        });

     btnUpdateFoodItem.setOnAction(event -> {
          FoodItem selectedItem = table.getSelectionModel().getSelectedItem();
    updateName.setText(selectedItem.getName());
    fia.updateFoodItem(selectedItem);
    });


    //Assemble our controls and display
    VBox root = new VBox();
    HBox tFields = new HBox();

    root.setSpacing(5);
    root.setPadding(new Insets(10, 10, 10, 10));
    root.setPrefSize(800, 600);
    root.getChildren().addAll(tFields, comboBox, table);

    tFields.setSpacing(5);
    tFields.setPadding(new Insets(10, 10, 10, 10));
    tFields.getChildren().addAll(tfName, tfPrice, btnAddFoodItem, btnDeleteFoodItem,btnUpdateFoodItem,updateName,updatePrice);

    table.setEditable(true);
    table.setItems(tableData);

    TableColumn idCol = new TableColumn("ID");
    TableColumn nameCol = new TableColumn("Name");
    TableColumn priceCol = new TableColumn("Price");

    idCol.setCellValueFactory(new PropertyValueFactory<FoodItem,String>("ID"));
    nameCol.setCellValueFactory(new PropertyValueFactory<FoodItem,String>("Name"));
    priceCol.setCellValueFactory(new PropertyValueFactory<FoodItem,String>("Price"));

    table.getColumns().addAll(idCol, nameCol, priceCol);

    Scene scene = new Scene(root);

    primaryStage.setTitle("My Shopping List");
    primaryStage.setScene(scene);
    primaryStage.show();

}

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

}

пакет javafxapplication4.persistence;

import java .util.List; import javafxapplication4.businesslogi c .FoodItem;

publi c class FoodItemAdapter {

private FoodPersistenceInterface foodItemPersistenceLayer;
public FoodItemAdapter(FoodPersistenceInterface fpi) {
foodItemPersistenceLayer = fpi;

}

public FoodItem createFoodItem(String name, float price) {

    List<FoodItem> tempListFoodItems = foodItemPersistenceLayer.retrieve();
    int newID = tempListFoodItems.get(tempListFoodItems.size()-1).getID() + 1;
    tempListFoodItems.add(new FoodItem(newID, name, price));
    foodItemPersistenceLayer.persist(tempListFoodItems);
    return tempListFoodItems.get(tempListFoodItems.size()-1);
} 

   public void createFoodItem(FoodItem f) {
   List<FoodItem> tempListFoodItems = foodItemPersistenceLayer.retrieve();
   tempListFoodItems.add(f);
   foodItemPersistenceLayer.persist(tempListFoodItems);

}

   public FoodItem readFoodItem(int ID) {
   List<FoodItem> tempListFoodItems = foodItemPersistenceLayer.retrieve();
   for (FoodItem t : tempListFoodItems) {
       if (t.getID() == ID) {
           return t;
       }
   }
   return null;} 
              public List<FoodItem> readAllFoodItems() {
   List<FoodItem> tempListFoodItems = foodItemPersistenceLayer.retrieve();       
   //There are no food items on file, so let's add a few
    if (tempListFoodItems.isEmpty()) {
        tempListFoodItems.add(new FoodItem(0, "Ham", 6.99F));
        tempListFoodItems.add(new FoodItem(1, "Eggs", 1.44F));
        tempListFoodItems.add(new FoodItem(2, "Cheese", 2.99F));
        tempListFoodItems.add(new FoodItem(3, "Bread", 2.07F));
        foodItemPersistenceLayer.persist(tempListFoodItems);
        System.out.println("4 food items created and saved");
    } else {
        System.out.println("Food items found on file, total = " + tempListFoodItems.size());
    }        
    return tempListFoodItems;
    }   

   public void updateFoodItem(FoodItem f){       
   List<FoodItem> tempListFoodItems = foodItemPersistenceLayer.retrieve();
   for (int i = 0; i < tempListFoodItems.size(); i++) {
       if (tempListFoodItems.get(i).getID() == f.getID()) {
           tempListFoodItems.set(i, f);
           foodItemPersistenceLayer.persist(tempListFoodItems);
           break;
         }
         }
         }   

         public void deleteFoodItem(FoodItem f) {
   List<FoodItem> tempListFoodItems = foodItemPersistenceLayer.retrieve();
   for (FoodItem t : tempListFoodItems) {
       if (t.getID() == f.getID()) {
           tempListFoodItems.remove(t);
           foodItemPersistenceLayer.persist(tempListFoodItems);
           break;
       }
   }

}

}

пакет javafxapplication4.persistence;

import java .util.List; import javafxapplication4.businesslogi c .FoodItem;

publi c interface FoodPersistenceInterface {

public abstract List<FoodItem> retrieve();
public abstract void persist(List<FoodItem> foodItems);

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...