I have products in one product-table that loads on start, from that table I want to add the select item from the first tableview to the cart-table.
So here is the problem, I know how to add a selected item from one table to another. But, if item already exists in a table it should increase the quantity and not add a duplicate row.
I've tried a couple of ways that kinda works except they always have bugs.
The logic is under addButton().
public class OrderController implements Initializable {
OrderRepository or = new OrderRepository();
ShoeRepository sr = new ShoeRepository();
LogInController logInController = new LogInController();
private int customer_ID;
private int total;
private List<ProductCart> productCarts = new LinkedList<>();
#FXML
private Label label_total;
#FXML
private Button button_makeOrder;
#FXML
private Button button_add;
#FXML
private Button button_remove;
#FXML
private TableView<ProductCart> table_cart;
#FXML
private TableView<Product> tableProduct;
#FXML
private TableColumn<Product, String> col_shoe;
#FXML
private TableColumn<Product, String> col_brand;
#FXML
private TableColumn<Product, String> col_color;
#FXML
private TableColumn<Product, Integer> col_size;
#FXML
private TableColumn<Product, Integer> col_price;
#FXML
private TableColumn<Product, Integer> col_stock;
#FXML
private TableColumn<ProductCart, String> col_cart_Shoe;
#FXML
private TableColumn<ProductCart, String> col_cart_brand;
#FXML
private TableColumn<ProductCart, String> col_cart_color;
#FXML
private TableColumn<ProductCart, Integer> col_cart_size;
#FXML
private TableColumn<ProductCart, Integer> col_cart_price;
#FXML
private TableColumn<ProductCart, Integer> col_cart_quantity;
public void a() {
System.out.println(customer_ID);
}
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
col_shoe.setCellValueFactory(new PropertyValueFactory<>("shoeName"));
col_brand.setCellValueFactory(new PropertyValueFactory<>("shoeBrand"));
col_color.setCellValueFactory(new PropertyValueFactory<>("shoeColor"));
col_size.setCellValueFactory(new PropertyValueFactory<>("shoeSize"));
col_price.setCellValueFactory(new PropertyValueFactory<>("shoePrice"));
col_stock.setCellValueFactory(new PropertyValueFactory<>("stock"));
col_cart_Shoe.setCellValueFactory(new PropertyValueFactory<>("name"));
col_cart_brand.setCellValueFactory(new PropertyValueFactory<>("brand"));
col_cart_color.setCellValueFactory(new PropertyValueFactory<>("color"));
col_cart_size.setCellValueFactory(new PropertyValueFactory<>("size"));
col_cart_price.setCellValueFactory(new PropertyValueFactory<>("price"));
col_cart_quantity.setCellValueFactory(new PropertyValueFactory<>("quantity"));
getProducts();
tableProduct.setItems(observableList);
customer_ID = logInController.getCustomer_ID();
}
ObservableList<Product> observableList = FXCollections.observableArrayList();
ObservableList<ProductCart> observableListC = FXCollections.observableArrayList();
public void getProducts() {
List<Product> products = new ArrayList<>();
List<Shoe> shoes = sr.getAllShoes();
shoes.forEach(shoe -> products.add(new Product(shoe.getShoe_ID(), shoe.getName(), shoe.getBrand().getName(),
shoe.getColor().getName(), shoe.getShoeSize().getShoeSize(), shoe.getInStock().getStock(),
shoe.getPrice().getPrice())));
products.forEach(product -> observableList.add(product));
}
public int getCustomer_ID() {
return customer_ID;
}
public void addButton() {
Product product = tableProduct.getSelectionModel().getSelectedItem();
ProductCart productCart = new ProductCart(product.getID(), product.getShoeName(), product.getShoeBrand(), product.getShoeColor(),
product.getShoeSize(),1, product.getShoePrice());
System.out.println(productCart.getName());
for (ProductCart item: productCarts) {
if (item.getName().equals(productCart.getName())) {
item.setQuantity(item.getQuantity() + 1);
table_cart.getItems().clear();
observableListC.remove(item);
observableListC.add(item);
}
else {
productCarts.add(item);
observableListC.add(item);
}
}
table_cart.setItems(observableListC);
updateTotal();
}
public void removeButton() {
}
public void makeOrder() {
}
public void updateTotal() {
total = 0;
List<ProductCart> productCarts = table_cart.getItems();
productCarts.forEach(productCart -> total += productCart.getPrice());
label_total.setText(total+"");
}
}
Changing only the quantity and stock in the tables works a lot better now.
However once an item is added to the table, adding the same row seems impossible without any bugs for me.
Version 1: Adding quantity to the existing row, unable to add new rows of other producs
Version 2: Being able to add rows, disables the ability to add quantity to existing row.
https://i.stack.imgur.com/EYoJ3.png
public void addButton() {
ProductCart productCart;
Product product = tableProduct.getSelectionModel().getSelectedItem();
productCart = new ProductCart(product.getID(), product.getShoeName(), product.getShoeBrand(),
product.getShoeColor(), product.getShoeSize(), product.getSold()+1, product.getShoePrice());
if (product.getStock() != 0) {
table_cart.getItems().add(productCart);
}
updateStock();
updateTotal();
}
Related
I have two Controller class(Controller and Dailog Controller). COntroller class has tableView. On Double click on Tableview row the Dialog popup. The dialogController class has two button i.e update and delete.
The Update button updating and deleting data in database. After updating or deleting i want to refresh tableview. The problem is tablview refresh method is in Controller class. So how can i refresh it?
public class Controller implements Initializable{
#FXML
private TabPane tabPane;
#FXML
private Tab createTaskTab;
#FXML
private TextArea textArea;
#FXML
private Button saveBtn;
#FXML
private Tab viewTasksTab;
#FXML
private TableView<Task> tableView;
#FXML
private TableColumn<Task, Integer> idColumn;
#FXML
private TableColumn<Task, String> dateColumn;
#FXML
private TableColumn<Task, String> timeColumn;
#FXML
private TableColumn<Task, String> taskColumn;
#FXML
private TableColumn<Task, String> statusColumn;
#FXML
void saveTask(ActionEvent event) {
String getTask = textArea.getText();
if(getTask.length() > 0)
{
MysqlConnection mysqlConnection = new MysqlConnection();
int count = mysqlConnection.insertTask(getTask);
if(count > 0)
{
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Saved");
alert.setContentText("Task Saved");
alert.show();
textArea.clear();
}
}
else
{
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("Empty TextArea");
alert.setContentText("Please write the task");
alert.show();
}
}
#FXML
public void viewTasks(Event e)
{
try{
tabPane.getSelectionModel().selectedItemProperty().addListener(
new ChangeListener<Tab>() {
#Override
public void changed(ObservableValue<? extends Tab> observable, Tab oldValue, Tab newValue) {
if(newValue == viewTasksTab)
{
refreshTable();
}
}
});
}catch(Exception exception)
{
System.out.println("Exception in viewTasks");
}
}
protected void refreshTable() {
MysqlConnection myconn = new MysqlConnection();
idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
dateColumn.setCellValueFactory(new PropertyValueFactory<>("date"));
timeColumn.setCellValueFactory(new PropertyValueFactory<>("time"));
taskColumn.setCellValueFactory(new PropertyValueFactory<>("task"));
statusColumn.setCellValueFactory(new PropertyValueFactory<>("status"));
tableView.setItems(myconn.fetchTasks());
}
#FXML
public void onEdit(MouseEvent event)
{
if(event.getClickCount() == 2){
Task selectedTask = tableView.getSelectionModel().getSelectedItem();
Scene scene;
Stage stage;
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("DialogBox.fxml"));
Parent root = (Parent) loader.load();
DialogBoxController dialog = loader.getController();
dialog.editTask(selectedTask);
scene = new Scene(root);
stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.setScene(scene);
stage.showAndWait();
} catch (IOException e) {
System.out.println("Exception in onEdit"+e.getMessage());
}
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
}
}
DialogController class:
[public class DialogBoxController implements Initializable{
#FXML
private Label idLabel;
#FXML
private Label dateLabel;
#FXML
private Label timeLabel;
#FXML
private ComboBox<String> statusComboBox;
#FXML
private TextArea textAreaDialog;
#FXML
private Button updateBtn;
#FXML
private Button deleteBtn;
private void closeStage(ActionEvent event) {
Node source = (Node) event.getSource();
Stage stage = (Stage) source.getScene().getWindow();
stage.close();
}
public void editTask(Task task)
{
idLabel.setText(""+task.getId());
dateLabel.setText(task.getDate());
timeLabel.setText(task.getTime());
textAreaDialog.setText(task.getTask());
statusComboBox.setValue(task.getStatus());
textAreaDialog.setEditable(false);
}
#FXML
public void update(ActionEvent event){
int taskID = Integer.parseInt(idLabel.getText());
String status = statusComboBox.getSelectionModel().getSelectedItem().toString();
MysqlConnection myconn = new MysqlConnection();
myconn.updateTask(taskID, status);
closeStage(event);
}
#FXML
public void delete(ActionEvent event){
int taskID = Integer.parseInt(idLabel.getText());
MysqlConnection myconn = new MysqlConnection();
myconn.deleteTask(taskID);
closeStage(event);
}
#Override
public void initialize(URL location, ResourceBundle resources) {
statusComboBox.getItems().addAll("Pending","Done","Aborted");
}
Snapcshot of Application
You can add this to the DialogBoxController class:
public class DialogBoxController {
private Controller controller;
public void setController(Controller controller){
this.controller = controller;
}
#FXML
public void delete(ActionEvent event){
// Your code
controller.refreshTable();
closeStage(event);
}}
And in the Controller:
DialogBoxController dialog = loader.getController();
dialog.editTask(selectedTask);
dialog.setController(this);
My problem is that I have two different classes : "Book" and "User".
I want to display Books in my table after clicking button "Show all books" and then all Users in this same table after clicking button "show all users". I don't know what type I should give in tableview and tablecolumn.
What can i put instead of "?" ?
public class WorkerPaneController implements Initializable {
#FXML
private TableView<?> tab;
#FXML
private TableColumn<?, ?> c3;
#FXML
private TableColumn<?, ?> c4;
#FXML
private TableColumn<?, ?> c5;
#FXML
private TableColumn<?, ?> c6;
#FXML
private Button test;
#FXML
private ComboBox<String> wybor;
#FXML
private Button show;
#FXML
private TableColumn<Data, ?> c1;
#FXML
private TableColumn<?, ?> c2;
#Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
this.wybor.getItems().addAll("Książek", "Egzemplarzy", "Czytelników",
"Pracowników");
}
#FXML
public void ChangeScene(ActionEvent event) throws IOException {
Parent userMenu =
FXMLLoader.load(getClass().getResource("/LibDB/view/UserPane.fxml"));
Stage s = new Stage();
s.setTitle("test");
s.setScene(new Scene(userMenu));
s.show();
}
#FXML
public void pokaz(ActionEvent event) throws IOException {
if (wybor.getValue() != null) {
switch (this.wybor.getValue()) {
case "Czytelników":
c1.setText("id_czytelnika");
c2.setText("Imie");
c3.setText("Nazwisko");
c4.setText("Wiek");
c5.setText("PESEL");
c6.setText("id_adresu");
break;
case "Pracowników":
c1.setText("id_czytelnika");
c2.setText("Imie");
c3.setText("Nazwisko");
c4.setText("Wiek");
c5.setText("PESEL");
c6.setText("id_adresu");
break;
case "Książek":
c1.setText("id_ksiazki");
c2.setText("Tytul");
c3.setText("Ilosc stron");
c4.setText("ISBN");
c5.setText("Rok Wydania");
c6.setText("id_wydawnictwa");
break;
case "Egzemplarzy":
c1.setText("id_egzemplarza");
c2.setText("Numer katalogowy");
c3.setText("id_Typ okladki");
c4.setText("Numer ksiazki");
c5.setText("opis");
c6.setText("Dostepnosc");
break;
}
} else {
System.out.println("test");
}
}
public void initPracownikow() {
// c1.setCellValueFactory(data ->
// data.getValue().getUzytkownicy().get(0).getImieProperty());
}
}
I have implemented fft for my school project(tuner), although, im not able to pass calculated frequency to GUI. I tried binding, keyframes, i just cant seem to get a grasp of it, im really new to java.
public class FrequencyBean {
double freq;
private SimpleDoubleProperty value = new SimpleDoubleProperty(this, "value");
public void setValue(double value){
this.value.set(value);
System.out.println(value+" set");
}
public DoubleProperty getDoublePropertyValue(){
System.out.println("gotvals");
return value;
}
public FrequencyBean(){
freq = 10.0;
}
that is part of my controller, also i got reccomended to use something called tight binding or so, which would be abstracting of this class. Is that good for my code?
This is my main controller:
public class Controller implements Initializable{
FrequencyBean fbean;
#FXML
private Label otherFq;
#FXML
private Text frequency;
#FXML
private Text sharpFq;
#FXML
private Rectangle sharp6;
#FXML
private Text flatFq;
#FXML
private Rectangle center_rectangle;
#FXML
private Rectangle sharp1;
#FXML
private Rectangle sharp2;
#FXML
private Rectangle sharp3;
#FXML
private Rectangle sharp4;
#FXML
private Rectangle sharp5;
#FXML
private Text centerFq;
#FXML
private Rectangle flat6;
#FXML
private Rectangle flat5;
#FXML
private Rectangle flat4;
#FXML
private Rectangle flat3;
#FXML
private Rectangle flat2;
#FXML
private Rectangle flat1;
#Override
public void initialize(URL location, ResourceBundle resources) {
fbean = new FrequencyBean();
otherFq = new Label();
frequency = new Text();
boolean stop = false;
InputThread input = new InputThread();
Task<Void> in = new Task<Void>() {
#Override
protected Void call() throws Exception {
input.run();
return null;
}
};
Thread th0 = new Thread(in);
th0.start();
frequency.textProperty().bind(fbean.getDoublePropertyValue());
}
Rewrite your FrequencyBean correctly as a 'JavaFX-Bean':
public class FrequencyBean {
private SimpleDoubleProperty frequency = new SimpleDoubleProperty();
/**
* #param frequency the frequency to set
*/
public void setFrequency(double value){
this.frequency.set(value);
}
/**
* #return the frequency as double
*/
public double getFrequency(){
return this.frequency.get();
}
/**
* #return the frequency property
*/
public DoubleProperty frequencyProperty(){
return value;
}
public FrequencyBean(){
frequency = 10.0;
}
}
As Jame_D pointed it out: don't initialize a control annotated with #FXML.
Just bind the control in question like so:
...
#FXML
TextField tf_Frequency;
...
fbean = new FrequencyBean(20.3);
tfFrequency.textProperty().bind(fbean.frequencyProperty().asString("%.2f"));
Note that this is correct if you need a uni-directional binding.
There is also a bindBidirectional method.
Trying to make a dictionary using JavaFx.
Here is my Controller class-
public class MainUIController implements Initializable {
DatabaseManager db=new DatabaseManager();
ObservableList<OvidhanMeaning> MeaningList;
#FXML
private TextField searchField;
#FXML
private ImageView searchIcon;
#FXML
private ImageView aboutIcon;
#FXML
private TableView<OvidhanMeaning> ovidhanTable;
#FXML
private TableColumn<OvidhanMeaning, String> englishCol;
#FXML
private TableColumn<OvidhanMeaning, String> banglaCol;
#Override
public void initialize(URL location, ResourceBundle resources) {
Image search = new Image(getClass().getResource("/images/search.png").toString(), true);
Image about = new Image(getClass().getResource("/images/about.png").toString(), true);
//Font bnFont = Font.loadFont(getClass().getResource("/fonts/Siyamrupali.ttf").toExternalForm(), 12);
Font bnFont = Font.loadFont(getClass().getResourceAsStream("/fonts/Siyamrupali.ttf"), 12);
searchIcon.setImage(search);
aboutIcon.setImage(about);
db.Connect("jdbc:sqlite::resource:ankurdb/bn_words.db");
ResultSet rs = db.GetResult("select en_word,bn_word from words");
MeaningList=FXCollections.observableArrayList();
try {
while(rs.next())
{
String enword = rs.getString("en_word");
String bnword = rs.getString("bn_word");
MeaningList.add(new OvidhanMeaning(enword,bnword));
englishCol.setCellValueFactory(new PropertyValueFactory<OvidhanMeaning, String>("enword"));
banglaCol.setCellValueFactory(new PropertyValueFactory<OvidhanMeaning, String>("bnword"));
ovidhanTable.setItems(MeaningList);
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println(MeaningList.size());
}
}
And here is my model class in which I loaded the data-
public class OvidhanMeaning {
private SimpleStringProperty enword;
private SimpleStringProperty bnword;
public OvidhanMeaning(String enword, String bnword) {
this.enword = new SimpleStringProperty(enword);
this.bnword = new SimpleStringProperty(bnword);
}
public String getenword() {
return enword.get();
}
public SimpleStringProperty enwordProperty() {
return enword;
}
public String getbnword() {
return bnword.get();
}
public SimpleStringProperty bnwordProperty() {
return bnword;
}
}
Now I'm trying to bind the searchField with the loaded MeaningList and populate the binded data into ovidhanTable.
How can I do this?
I have a TableView with three TableColumns. There is an ObservableList named "sensorDataList " in MainApp.java that stores the objects to be shown in the TableView. With the following code, only the first TableColumn named "idColumn" doesn't show the values from the observable list, however, the other two TableColumns works fine.
MainApp.java (this has an "ObservableList" of Sensor objects (see Sensor.java). Also this class has the method named "showSensorDialog()" which loads the .fxml file that has the TableView in question. FYI, this method is invoked by a button in other controller.)
public class MainApp extends Application {
private Stage primaryStage;
private Stage sensorDialogStage;
private ObservableList<sensor> sensorDataList = FXCollections.observableArrayList();
public MainApp(){
sensorDataList.add(new sensor("testText","1 1 0.7", "0 0 1"));
}
public ObservableList<Sensor> getSensorDataList(){return sensorDataList;}
public void showSensorDialog() {
try {
FXMLLoader loader = new FXMLLoader(MainApp.class.getResource("/view/SensorDialog.fxml"));
Object object = loader.load();
sensorDialogStage = new Stage();
Scene scene = new Scene((Parent) object);
sensorDialogStage.setScene(scene);
SensorDialogController controller = loader.getController();
controller.setSensorDialogStage(sensorDialogStage);
controller.setMainApp(this); // this line connects the ObservableList to the TableView.
sensorDialogStage.showAndWait();
} catch (IOException e) {}
}
}
SensorDialogController.java
public class SensorDialogController implements Initializable {
#FXML
private TableView<Sensor> sensorTable;
#FXML
private TableColumn<Sensor, String> idColumn;
#FXML
private TableColumn<Sensor, String> locationColumn;
#FXML
private TableColumn<Sensor, String> directionColumn;
private MainApp mainApp;
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
sensorTable.setItems(mainApp.getSensorDataList()); // ObservableList and TableView gets connected.
}
#Override
public void initialize(URL url, ResourceBundle rb){
idColumn.setCellValueFactory(new PropertyValueFactory<Sensor, String>("id"));
locationColumn.setCellValueFactory(new PropertyValueFactory<Sensor, String>("location"));
directionColumn.setCellValueFactory(new PropertyValueFactory<Sensor, String>("direction"));
}
}
Sensor.java
public class Sensor{
private SimpleStringProperty id;
private SimpleStringProperty location;
private SimpleStringProperty direction;
public Sensor(String i, String loc, String dir){
this.id = new SimpleStringProperty(i);
this.location = new SimpleStringProperty(loc);
this.direction = new SimpleStringProperty(dir);
}
}