java-fx-samples/src/moviedatabase/LayoutController.java
2019-08-09 05:22:38 +02:00

121 lines
3.4 KiB
Java

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package moviedatabase;
import java.net.URL;
import java.util.Random;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
/**
* FXML Controller class
*
* @author mschw
*/
public class LayoutController implements Initializable {
@FXML
private ListView<Item> lvItems;
@FXML
private Label lblOnStock;
@FXML
private Label lblKost;
@FXML
private Label lblID;
@FXML
private Button btnNew;
@FXML
private CheckBox cbRand;
public static ObservableList<Item> obsItems = FXCollections.observableArrayList();
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
if (obsItems.isEmpty()) {
obsItems.add(new Item("TestItem", 1, 50, 200));
obsItems.add(new Item("Prozessoren", 2, 150, 20));
obsItems.add(new Item("Mütze", 3, 15, 30));
}
/*
obsItems.addListener((ListChangeListener.Change<? extends Item> c) -> {
this.lvItems.refresh();
});
*/
lvItems.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
lvItems.setItems(obsItems);
lvItems.refresh();
}
@FXML
private void handleNew(ActionEvent event) {
if (cbRand.isSelected()) {
obsItems.add(new Item(
getRandomName(),
new Random().nextInt(),
new Random().nextInt(),
new Random().nextInt()));
} else {
Main.changeScene("AddLayout.fxml", event, this.getClass());
}
}
@FXML
private void handleMouseClickedItems(MouseEvent event) {
Item i = lvItems.getSelectionModel().getSelectedItem();
if (i != null) {
System.out.println(i);
lblID.setText("ID: " + i.getId());
lblKost.setText("Kosten: " + i.getKost());
lblOnStock.setText("Auf lager: " + i.getOnStock());
}
}
@FXML
private void handleDelete(ActionEvent event) {
Item i;
if ((i = lvItems.getSelectionModel().getSelectedItem()) != null) {
obsItems.remove(i);
}
}
private String getRandomName() {
String pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
String result = "";
for (int i = 0; i < 10; i++) {
result += pool.charAt(new Random().nextInt(pool.length()));
}
return result;
}
@FXML
private void handleKeyPressedItems(KeyEvent event) {
Item i = lvItems.getSelectionModel().getSelectedItem();
if (i != null) {
System.out.println(i);
lblID.setText("ID: " + i.getId());
lblKost.setText("Kosten: " + i.getKost());
lblOnStock.setText("Auf lager: " + i.getOnStock());
}
}
}