Coloring Rows in TableView











up vote
-1
down vote

favorite












I want to color the rows of my tableview. But now it is that I need to click on the table or any other element first to get the tableView colored. I use Platform.runLater for adding, deleting and changing something.
For the initialize to get the colors even shown I need to do:



tableView.getColumns().get(3).setVisible(true);
tableView.getColumns().get(3).setVisible(false);

package application.controller.DetailsController;

import java.io.IOException;
import java.net.URL;
import java.sql.Timestamp;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.ArrayList;
import java.util.Calendar;
import application.Main;
import application.SceneSwitcher;
import application.DB.DBManager;
import application.models.*;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Labeled;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TableRow;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.StringConverter;

public class DetailsController implements Initializable { // Sascha

@FXML Label notierter;
@FXML TextField Notiz;
@FXML TextField filterField;
@FXML Button addDetails;
@FXML Button deleteDetails;
@FXML Button uebersichtSemester;
@FXML Button uebersichtGruppe;
@FXML Button uebersichtStudierende;
@FXML ComboBox<Details> Zuordnungsauswahl;

@FXML TableView<Details> tableView;
@FXML TableColumn<Details, String> IDColumn;
@FXML TableColumn<Details, String> NotizColumn;
@FXML TableColumn<Details, Timestamp> DatumColumn;
@FXML TableColumn<Details, Integer> BewertungColumn;

DBManager connector = Main.connector;
SceneSwitcher sc = new SceneSwitcher();
static Groupage groupage = null; // dürfen nicht initialsiert werden, sonst != null = setter aktiv
static Student student = null;
static Group group = null;
static Semester semester = null;

public static void setGroupage(Groupage g) {
groupage = g;
}

public static void setStudent(Student st) {
student = st;
}

public static void setGroup(Group gr) {
group = gr;
}

public static void setSemester(Semester se) {
semester = se;
}

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

// set up the columns in the table
IDColumn.setCellValueFactory(new PropertyValueFactory<Details, String>("id"));
NotizColumn.setCellValueFactory(new PropertyValueFactory<Details, String>("bemerkung"));
DatumColumn.setCellValueFactory(new PropertyValueFactory<Details, Timestamp>("date"));
DatumColumn.setCellFactory((TableColumn<Details, Timestamp> column) -> {
return new TableCell<Details, Timestamp>() {
@Override
protected void updateItem(Timestamp item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
} else {
setText(item.toLocalDateTime().format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss")));
}
}
};
});
BewertungColumn.setCellValueFactory(new PropertyValueFactory<Details, Integer>("bewertung"));
tableView.getColumns().get(3).setVisible(true);

tableView.setRowFactory(row -> new TableRow<Details>() {
@Override
public void updateItem(Details item, boolean empty) {
super.updateItem(item, empty);

if (item == null || empty) {
tableView.getColumns().get(3).setVisible(false);
setStyle("");
} else {
// Now 'item' has all the info of the Person in this row
if (item.getBewertung() == 0) {
// We apply now the changes in all the cells of the row
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.BLACK);
getChildren().get(i).setStyle("-fx-background-color: #D8D8D8");
}
} else if (item.getBewertung() == 1) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #81F781");
}
} else if (item.getBewertung() == 2) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #F78181");
}
} else if (item.getBewertung() == 3) {
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: white");
}
}
}


}
});


deleteDetails.setDisable(true);

if (groupage != null) {
tableView.setItems(getDetails());
notierter.setText(groupage.getBezeichnung());
} else if (student != null) {
tableView.setItems(getDetails());
notierter.setText(student.getVn() + " " + student.getNn());
} else if (group != null) {
tableView.setItems(getDetails());
notierter.setText(group.getBezeichnung());
} else if (semester != null) {
tableView.setItems(getDetails());
notierter.setText(semester.getBezeichnung());
}

tableView.setEditable(true);
IDColumn.setEditable(false);
NotizColumn.setCellFactory(TextFieldTableCell.forTableColumn());

// This will allow the table to select multiple rows at once
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

// ComboBox Implementierung
Zuordnungsauswahl.setItems(getDetailsForComboBox());
Zuordnungsauswahl.setConverter(new StringConverter<Details>() {

@Override
public String toString(Details object) {
if (object.getId() == 0) {
return "Normal";
} else if (object.getId() == 1) {
return "Gut";
} else if (object.getId() == 2) {
return "Schlecht";
} else {
return "Keine Zuordnung";
}
}

@Override
public Details fromString(String arg0) { // nur implementiert, weil es muss
return null;
}
});

FilteredList<Details> filteredData = new FilteredList<>(getDetails(), p -> true);

// 2. Set the filter Predicate whenever the filter changes.
filterField.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(details -> {
// If filter text is empty, display all persons.
if (newValue == null || newValue.isEmpty()) {
return true;
}

String lowerCaseFilter = newValue.toLowerCase();

if (details.getBemerkung().toLowerCase().contains(lowerCaseFilter)) {
return true;
}
return false;
});
});

// 3. Wrap the FilteredList in a SortedList.
SortedList<Details> sortedData = new SortedList<>(filteredData);

// 4. Bind the SortedList comparator to the TableView comparator.
sortedData.comparatorProperty().bind(tableView.comparatorProperty());

// 5. Add sorted (and filtered) data to the table.
tableView.setItems(sortedData);
}

public ObservableList<Details> getDetails() {
ObservableList<Details> details = FXCollections.observableArrayList();

if (groupage != null) {
List<Details> merge = connector.showDetailsAll(groupage);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
} else if (student != null) {
List<Details> merge = connector.showDetailsAll(student);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
} else if (group != null) {
List<Details> merge = connector.showDetailsAll(group);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
} else if (semester != null) {
List<Details> merge = connector.showDetailsAll(semester);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
}

return details;
}

public ObservableList<Details> getDetailsForComboBox() {
ObservableList<Details> details = FXCollections.observableArrayList();
Details normal = new Details(0);
Details gut = new Details(1);
Details schlecht = new Details(2);
Details keineZuordnung = new Details(3);

List<Details> merge = new ArrayList<Details>();
merge.add(normal);
merge.add(gut);
merge.add(schlecht);
merge.add(keineZuordnung);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}

return details;
}

public void userClickedOnTable() {
deleteDetails.setDisable(false);
}

public void buttonAddDetails() {
if (testOnFirstCharacter(Notiz.getText()) == false) {
Alert alert = new Alert(AlertType.ERROR);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/application/resources/icons8-blockchain-technology-64.png"));
alert.setTitle("Eingabefehler");
alert.setHeaderText("Ups, ein Fehler ist aufgetreten");
alert.setContentText("Das erste Zeichen darf nicht leer sein.");
alert.show();
} else {
Details det = new Details();

det.setGroupage(groupage);
det.setSemester(semester);
det.setGroup(group);
det.setStudent(student);
det.setBemerkung(Notiz.getText());
if (Zuordnungsauswahl.getValue() == null) {
det.setBewertung(3);
} else {
det.setBewertung(Zuordnungsauswahl.getValue().getId());
}

Calendar calendar = Calendar.getInstance();

Timestamp timestamp = new Timestamp(calendar.getTimeInMillis());

det.setDate(timestamp);

connector.addDetails(det);
colorFix(null);
initialize(null, null);
Notiz.clear();
}
}

public void buttonDeleteDetails() {
Alert alert = new Alert(AlertType.CONFIRMATION);

// Für das Icon im Alert
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/application/resources/icons8-blockchain-technology-64.png"));

alert.setTitle("Bestätigung erforderlich");
alert.setHeaderText("Soll diese Notiz wirklich gelöscht werden?");

ButtonType buttonTypeJa = new ButtonType("Ja");
ButtonType buttonTypeNein = new ButtonType("Nein");
ButtonType buttonTypeAbbrechen = new ButtonType("Abbrechen", ButtonData.CANCEL_CLOSE);

alert.getButtonTypes().setAll(buttonTypeJa, buttonTypeNein, buttonTypeAbbrechen);

Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeJa) {
Details det = tableView.getSelectionModel().getSelectedItem();
connector.deleteDetails(det);
colorFix(null);
initialize(null, null);
} else if (result.get() == buttonTypeNein) {
alert.close();
}
}

public void changeNotiz(CellEditEvent<?, ?> edittedCell) {
Details details = tableView.getSelectionModel().getSelectedItem();
if (testOnFirstCharacter(edittedCell.getNewValue().toString())) {
details.setBemerkung(edittedCell.getNewValue().toString());
Calendar calendar = Calendar.getInstance();

Timestamp timestamp = new Timestamp(calendar.getTimeInMillis());
details.setDate(timestamp);
connector.changeDetails(details);
colorFix(null);
initialize(null, null);
} else {
Alert alert = new Alert(AlertType.ERROR);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/application/resources/icons8-blockchain-technology-64.png"));
alert.setTitle("Eingabefehler");
alert.setHeaderText("Ups, ein Fehler ist aufgetreten");
alert.setContentText("Das erste Zeichen darf nicht leer sein.");
alert.show();
}
}

public boolean testOnFirstCharacter(String text) {
if (text.charAt(0) == ' ') {
return false;
}
return true;
}

public void buttonZurueck(ActionEvent event) throws IOException {
setGroupage(null);
setStudent(null);
setGroup(null);
setSemester(null);

sc.switchToZurueck(event);
}

public void colorFix(ActionEvent e) {
Platform.runLater(() -> {
tableView.setRowFactory(row -> new TableRow<Details>() {
@Override
public void updateItem(Details item, boolean empty) {
super.updateItem(item, empty);

if (item == null || empty) {
setStyle("");
} else {
// Now 'item' has all the info of the Person in this row
if (item.getBewertung() == 0) {
// We apply now the changes in all the cells of the row
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.BLACK);
getChildren().get(i).setStyle("-fx-background-color: #D8D8D8");
}
} else if (item.getBewertung() == 1) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #81F781");
}
} else if (item.getBewertung() == 2) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #F78181");
}
} else if (item.getBewertung() == 3) {
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: white");
}
}
}
}
});
});
}
}









share|improve this question




















  • 1




    Please try to write a minimal, complete and verifiable example : stackoverflow.com/help/mcve
    – Calips
    Nov 22 at 13:48










  • unrelated to your problem: please learn java naming conventions and stick to them
    – kleopatra
    Nov 22 at 14:22










  • related, though only general advice (as long as your example it's neither minimal nor standalone, I wont give it a closer look, sry) : a) if you need setVisible(false)/(true) there's something wrong in your setup b) there have been several QAs recently related to conditional row styles, please search the site and apply what you learn from the answers
    – kleopatra
    Nov 22 at 14:26












  • I researched like the whole stackOverflow and even my teacher at the university couldn't figure out the problem. Of course I need setVisible when I use the updateItem method.
    – CptDayDreamer
    Nov 22 at 14:32










  • Hi, welcome to Stack Overflow! I've removed the redundant tag from your title, and also removed the blockquote at the end of the post ;)
    – Federico Grandi
    Nov 22 at 19:16















up vote
-1
down vote

favorite












I want to color the rows of my tableview. But now it is that I need to click on the table or any other element first to get the tableView colored. I use Platform.runLater for adding, deleting and changing something.
For the initialize to get the colors even shown I need to do:



tableView.getColumns().get(3).setVisible(true);
tableView.getColumns().get(3).setVisible(false);

package application.controller.DetailsController;

import java.io.IOException;
import java.net.URL;
import java.sql.Timestamp;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.ArrayList;
import java.util.Calendar;
import application.Main;
import application.SceneSwitcher;
import application.DB.DBManager;
import application.models.*;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Labeled;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TableRow;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.StringConverter;

public class DetailsController implements Initializable { // Sascha

@FXML Label notierter;
@FXML TextField Notiz;
@FXML TextField filterField;
@FXML Button addDetails;
@FXML Button deleteDetails;
@FXML Button uebersichtSemester;
@FXML Button uebersichtGruppe;
@FXML Button uebersichtStudierende;
@FXML ComboBox<Details> Zuordnungsauswahl;

@FXML TableView<Details> tableView;
@FXML TableColumn<Details, String> IDColumn;
@FXML TableColumn<Details, String> NotizColumn;
@FXML TableColumn<Details, Timestamp> DatumColumn;
@FXML TableColumn<Details, Integer> BewertungColumn;

DBManager connector = Main.connector;
SceneSwitcher sc = new SceneSwitcher();
static Groupage groupage = null; // dürfen nicht initialsiert werden, sonst != null = setter aktiv
static Student student = null;
static Group group = null;
static Semester semester = null;

public static void setGroupage(Groupage g) {
groupage = g;
}

public static void setStudent(Student st) {
student = st;
}

public static void setGroup(Group gr) {
group = gr;
}

public static void setSemester(Semester se) {
semester = se;
}

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

// set up the columns in the table
IDColumn.setCellValueFactory(new PropertyValueFactory<Details, String>("id"));
NotizColumn.setCellValueFactory(new PropertyValueFactory<Details, String>("bemerkung"));
DatumColumn.setCellValueFactory(new PropertyValueFactory<Details, Timestamp>("date"));
DatumColumn.setCellFactory((TableColumn<Details, Timestamp> column) -> {
return new TableCell<Details, Timestamp>() {
@Override
protected void updateItem(Timestamp item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
} else {
setText(item.toLocalDateTime().format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss")));
}
}
};
});
BewertungColumn.setCellValueFactory(new PropertyValueFactory<Details, Integer>("bewertung"));
tableView.getColumns().get(3).setVisible(true);

tableView.setRowFactory(row -> new TableRow<Details>() {
@Override
public void updateItem(Details item, boolean empty) {
super.updateItem(item, empty);

if (item == null || empty) {
tableView.getColumns().get(3).setVisible(false);
setStyle("");
} else {
// Now 'item' has all the info of the Person in this row
if (item.getBewertung() == 0) {
// We apply now the changes in all the cells of the row
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.BLACK);
getChildren().get(i).setStyle("-fx-background-color: #D8D8D8");
}
} else if (item.getBewertung() == 1) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #81F781");
}
} else if (item.getBewertung() == 2) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #F78181");
}
} else if (item.getBewertung() == 3) {
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: white");
}
}
}


}
});


deleteDetails.setDisable(true);

if (groupage != null) {
tableView.setItems(getDetails());
notierter.setText(groupage.getBezeichnung());
} else if (student != null) {
tableView.setItems(getDetails());
notierter.setText(student.getVn() + " " + student.getNn());
} else if (group != null) {
tableView.setItems(getDetails());
notierter.setText(group.getBezeichnung());
} else if (semester != null) {
tableView.setItems(getDetails());
notierter.setText(semester.getBezeichnung());
}

tableView.setEditable(true);
IDColumn.setEditable(false);
NotizColumn.setCellFactory(TextFieldTableCell.forTableColumn());

// This will allow the table to select multiple rows at once
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

// ComboBox Implementierung
Zuordnungsauswahl.setItems(getDetailsForComboBox());
Zuordnungsauswahl.setConverter(new StringConverter<Details>() {

@Override
public String toString(Details object) {
if (object.getId() == 0) {
return "Normal";
} else if (object.getId() == 1) {
return "Gut";
} else if (object.getId() == 2) {
return "Schlecht";
} else {
return "Keine Zuordnung";
}
}

@Override
public Details fromString(String arg0) { // nur implementiert, weil es muss
return null;
}
});

FilteredList<Details> filteredData = new FilteredList<>(getDetails(), p -> true);

// 2. Set the filter Predicate whenever the filter changes.
filterField.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(details -> {
// If filter text is empty, display all persons.
if (newValue == null || newValue.isEmpty()) {
return true;
}

String lowerCaseFilter = newValue.toLowerCase();

if (details.getBemerkung().toLowerCase().contains(lowerCaseFilter)) {
return true;
}
return false;
});
});

// 3. Wrap the FilteredList in a SortedList.
SortedList<Details> sortedData = new SortedList<>(filteredData);

// 4. Bind the SortedList comparator to the TableView comparator.
sortedData.comparatorProperty().bind(tableView.comparatorProperty());

// 5. Add sorted (and filtered) data to the table.
tableView.setItems(sortedData);
}

public ObservableList<Details> getDetails() {
ObservableList<Details> details = FXCollections.observableArrayList();

if (groupage != null) {
List<Details> merge = connector.showDetailsAll(groupage);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
} else if (student != null) {
List<Details> merge = connector.showDetailsAll(student);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
} else if (group != null) {
List<Details> merge = connector.showDetailsAll(group);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
} else if (semester != null) {
List<Details> merge = connector.showDetailsAll(semester);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
}

return details;
}

public ObservableList<Details> getDetailsForComboBox() {
ObservableList<Details> details = FXCollections.observableArrayList();
Details normal = new Details(0);
Details gut = new Details(1);
Details schlecht = new Details(2);
Details keineZuordnung = new Details(3);

List<Details> merge = new ArrayList<Details>();
merge.add(normal);
merge.add(gut);
merge.add(schlecht);
merge.add(keineZuordnung);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}

return details;
}

public void userClickedOnTable() {
deleteDetails.setDisable(false);
}

public void buttonAddDetails() {
if (testOnFirstCharacter(Notiz.getText()) == false) {
Alert alert = new Alert(AlertType.ERROR);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/application/resources/icons8-blockchain-technology-64.png"));
alert.setTitle("Eingabefehler");
alert.setHeaderText("Ups, ein Fehler ist aufgetreten");
alert.setContentText("Das erste Zeichen darf nicht leer sein.");
alert.show();
} else {
Details det = new Details();

det.setGroupage(groupage);
det.setSemester(semester);
det.setGroup(group);
det.setStudent(student);
det.setBemerkung(Notiz.getText());
if (Zuordnungsauswahl.getValue() == null) {
det.setBewertung(3);
} else {
det.setBewertung(Zuordnungsauswahl.getValue().getId());
}

Calendar calendar = Calendar.getInstance();

Timestamp timestamp = new Timestamp(calendar.getTimeInMillis());

det.setDate(timestamp);

connector.addDetails(det);
colorFix(null);
initialize(null, null);
Notiz.clear();
}
}

public void buttonDeleteDetails() {
Alert alert = new Alert(AlertType.CONFIRMATION);

// Für das Icon im Alert
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/application/resources/icons8-blockchain-technology-64.png"));

alert.setTitle("Bestätigung erforderlich");
alert.setHeaderText("Soll diese Notiz wirklich gelöscht werden?");

ButtonType buttonTypeJa = new ButtonType("Ja");
ButtonType buttonTypeNein = new ButtonType("Nein");
ButtonType buttonTypeAbbrechen = new ButtonType("Abbrechen", ButtonData.CANCEL_CLOSE);

alert.getButtonTypes().setAll(buttonTypeJa, buttonTypeNein, buttonTypeAbbrechen);

Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeJa) {
Details det = tableView.getSelectionModel().getSelectedItem();
connector.deleteDetails(det);
colorFix(null);
initialize(null, null);
} else if (result.get() == buttonTypeNein) {
alert.close();
}
}

public void changeNotiz(CellEditEvent<?, ?> edittedCell) {
Details details = tableView.getSelectionModel().getSelectedItem();
if (testOnFirstCharacter(edittedCell.getNewValue().toString())) {
details.setBemerkung(edittedCell.getNewValue().toString());
Calendar calendar = Calendar.getInstance();

Timestamp timestamp = new Timestamp(calendar.getTimeInMillis());
details.setDate(timestamp);
connector.changeDetails(details);
colorFix(null);
initialize(null, null);
} else {
Alert alert = new Alert(AlertType.ERROR);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/application/resources/icons8-blockchain-technology-64.png"));
alert.setTitle("Eingabefehler");
alert.setHeaderText("Ups, ein Fehler ist aufgetreten");
alert.setContentText("Das erste Zeichen darf nicht leer sein.");
alert.show();
}
}

public boolean testOnFirstCharacter(String text) {
if (text.charAt(0) == ' ') {
return false;
}
return true;
}

public void buttonZurueck(ActionEvent event) throws IOException {
setGroupage(null);
setStudent(null);
setGroup(null);
setSemester(null);

sc.switchToZurueck(event);
}

public void colorFix(ActionEvent e) {
Platform.runLater(() -> {
tableView.setRowFactory(row -> new TableRow<Details>() {
@Override
public void updateItem(Details item, boolean empty) {
super.updateItem(item, empty);

if (item == null || empty) {
setStyle("");
} else {
// Now 'item' has all the info of the Person in this row
if (item.getBewertung() == 0) {
// We apply now the changes in all the cells of the row
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.BLACK);
getChildren().get(i).setStyle("-fx-background-color: #D8D8D8");
}
} else if (item.getBewertung() == 1) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #81F781");
}
} else if (item.getBewertung() == 2) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #F78181");
}
} else if (item.getBewertung() == 3) {
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: white");
}
}
}
}
});
});
}
}









share|improve this question




















  • 1




    Please try to write a minimal, complete and verifiable example : stackoverflow.com/help/mcve
    – Calips
    Nov 22 at 13:48










  • unrelated to your problem: please learn java naming conventions and stick to them
    – kleopatra
    Nov 22 at 14:22










  • related, though only general advice (as long as your example it's neither minimal nor standalone, I wont give it a closer look, sry) : a) if you need setVisible(false)/(true) there's something wrong in your setup b) there have been several QAs recently related to conditional row styles, please search the site and apply what you learn from the answers
    – kleopatra
    Nov 22 at 14:26












  • I researched like the whole stackOverflow and even my teacher at the university couldn't figure out the problem. Of course I need setVisible when I use the updateItem method.
    – CptDayDreamer
    Nov 22 at 14:32










  • Hi, welcome to Stack Overflow! I've removed the redundant tag from your title, and also removed the blockquote at the end of the post ;)
    – Federico Grandi
    Nov 22 at 19:16













up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











I want to color the rows of my tableview. But now it is that I need to click on the table or any other element first to get the tableView colored. I use Platform.runLater for adding, deleting and changing something.
For the initialize to get the colors even shown I need to do:



tableView.getColumns().get(3).setVisible(true);
tableView.getColumns().get(3).setVisible(false);

package application.controller.DetailsController;

import java.io.IOException;
import java.net.URL;
import java.sql.Timestamp;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.ArrayList;
import java.util.Calendar;
import application.Main;
import application.SceneSwitcher;
import application.DB.DBManager;
import application.models.*;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Labeled;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TableRow;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.StringConverter;

public class DetailsController implements Initializable { // Sascha

@FXML Label notierter;
@FXML TextField Notiz;
@FXML TextField filterField;
@FXML Button addDetails;
@FXML Button deleteDetails;
@FXML Button uebersichtSemester;
@FXML Button uebersichtGruppe;
@FXML Button uebersichtStudierende;
@FXML ComboBox<Details> Zuordnungsauswahl;

@FXML TableView<Details> tableView;
@FXML TableColumn<Details, String> IDColumn;
@FXML TableColumn<Details, String> NotizColumn;
@FXML TableColumn<Details, Timestamp> DatumColumn;
@FXML TableColumn<Details, Integer> BewertungColumn;

DBManager connector = Main.connector;
SceneSwitcher sc = new SceneSwitcher();
static Groupage groupage = null; // dürfen nicht initialsiert werden, sonst != null = setter aktiv
static Student student = null;
static Group group = null;
static Semester semester = null;

public static void setGroupage(Groupage g) {
groupage = g;
}

public static void setStudent(Student st) {
student = st;
}

public static void setGroup(Group gr) {
group = gr;
}

public static void setSemester(Semester se) {
semester = se;
}

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

// set up the columns in the table
IDColumn.setCellValueFactory(new PropertyValueFactory<Details, String>("id"));
NotizColumn.setCellValueFactory(new PropertyValueFactory<Details, String>("bemerkung"));
DatumColumn.setCellValueFactory(new PropertyValueFactory<Details, Timestamp>("date"));
DatumColumn.setCellFactory((TableColumn<Details, Timestamp> column) -> {
return new TableCell<Details, Timestamp>() {
@Override
protected void updateItem(Timestamp item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
} else {
setText(item.toLocalDateTime().format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss")));
}
}
};
});
BewertungColumn.setCellValueFactory(new PropertyValueFactory<Details, Integer>("bewertung"));
tableView.getColumns().get(3).setVisible(true);

tableView.setRowFactory(row -> new TableRow<Details>() {
@Override
public void updateItem(Details item, boolean empty) {
super.updateItem(item, empty);

if (item == null || empty) {
tableView.getColumns().get(3).setVisible(false);
setStyle("");
} else {
// Now 'item' has all the info of the Person in this row
if (item.getBewertung() == 0) {
// We apply now the changes in all the cells of the row
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.BLACK);
getChildren().get(i).setStyle("-fx-background-color: #D8D8D8");
}
} else if (item.getBewertung() == 1) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #81F781");
}
} else if (item.getBewertung() == 2) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #F78181");
}
} else if (item.getBewertung() == 3) {
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: white");
}
}
}


}
});


deleteDetails.setDisable(true);

if (groupage != null) {
tableView.setItems(getDetails());
notierter.setText(groupage.getBezeichnung());
} else if (student != null) {
tableView.setItems(getDetails());
notierter.setText(student.getVn() + " " + student.getNn());
} else if (group != null) {
tableView.setItems(getDetails());
notierter.setText(group.getBezeichnung());
} else if (semester != null) {
tableView.setItems(getDetails());
notierter.setText(semester.getBezeichnung());
}

tableView.setEditable(true);
IDColumn.setEditable(false);
NotizColumn.setCellFactory(TextFieldTableCell.forTableColumn());

// This will allow the table to select multiple rows at once
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

// ComboBox Implementierung
Zuordnungsauswahl.setItems(getDetailsForComboBox());
Zuordnungsauswahl.setConverter(new StringConverter<Details>() {

@Override
public String toString(Details object) {
if (object.getId() == 0) {
return "Normal";
} else if (object.getId() == 1) {
return "Gut";
} else if (object.getId() == 2) {
return "Schlecht";
} else {
return "Keine Zuordnung";
}
}

@Override
public Details fromString(String arg0) { // nur implementiert, weil es muss
return null;
}
});

FilteredList<Details> filteredData = new FilteredList<>(getDetails(), p -> true);

// 2. Set the filter Predicate whenever the filter changes.
filterField.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(details -> {
// If filter text is empty, display all persons.
if (newValue == null || newValue.isEmpty()) {
return true;
}

String lowerCaseFilter = newValue.toLowerCase();

if (details.getBemerkung().toLowerCase().contains(lowerCaseFilter)) {
return true;
}
return false;
});
});

// 3. Wrap the FilteredList in a SortedList.
SortedList<Details> sortedData = new SortedList<>(filteredData);

// 4. Bind the SortedList comparator to the TableView comparator.
sortedData.comparatorProperty().bind(tableView.comparatorProperty());

// 5. Add sorted (and filtered) data to the table.
tableView.setItems(sortedData);
}

public ObservableList<Details> getDetails() {
ObservableList<Details> details = FXCollections.observableArrayList();

if (groupage != null) {
List<Details> merge = connector.showDetailsAll(groupage);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
} else if (student != null) {
List<Details> merge = connector.showDetailsAll(student);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
} else if (group != null) {
List<Details> merge = connector.showDetailsAll(group);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
} else if (semester != null) {
List<Details> merge = connector.showDetailsAll(semester);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
}

return details;
}

public ObservableList<Details> getDetailsForComboBox() {
ObservableList<Details> details = FXCollections.observableArrayList();
Details normal = new Details(0);
Details gut = new Details(1);
Details schlecht = new Details(2);
Details keineZuordnung = new Details(3);

List<Details> merge = new ArrayList<Details>();
merge.add(normal);
merge.add(gut);
merge.add(schlecht);
merge.add(keineZuordnung);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}

return details;
}

public void userClickedOnTable() {
deleteDetails.setDisable(false);
}

public void buttonAddDetails() {
if (testOnFirstCharacter(Notiz.getText()) == false) {
Alert alert = new Alert(AlertType.ERROR);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/application/resources/icons8-blockchain-technology-64.png"));
alert.setTitle("Eingabefehler");
alert.setHeaderText("Ups, ein Fehler ist aufgetreten");
alert.setContentText("Das erste Zeichen darf nicht leer sein.");
alert.show();
} else {
Details det = new Details();

det.setGroupage(groupage);
det.setSemester(semester);
det.setGroup(group);
det.setStudent(student);
det.setBemerkung(Notiz.getText());
if (Zuordnungsauswahl.getValue() == null) {
det.setBewertung(3);
} else {
det.setBewertung(Zuordnungsauswahl.getValue().getId());
}

Calendar calendar = Calendar.getInstance();

Timestamp timestamp = new Timestamp(calendar.getTimeInMillis());

det.setDate(timestamp);

connector.addDetails(det);
colorFix(null);
initialize(null, null);
Notiz.clear();
}
}

public void buttonDeleteDetails() {
Alert alert = new Alert(AlertType.CONFIRMATION);

// Für das Icon im Alert
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/application/resources/icons8-blockchain-technology-64.png"));

alert.setTitle("Bestätigung erforderlich");
alert.setHeaderText("Soll diese Notiz wirklich gelöscht werden?");

ButtonType buttonTypeJa = new ButtonType("Ja");
ButtonType buttonTypeNein = new ButtonType("Nein");
ButtonType buttonTypeAbbrechen = new ButtonType("Abbrechen", ButtonData.CANCEL_CLOSE);

alert.getButtonTypes().setAll(buttonTypeJa, buttonTypeNein, buttonTypeAbbrechen);

Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeJa) {
Details det = tableView.getSelectionModel().getSelectedItem();
connector.deleteDetails(det);
colorFix(null);
initialize(null, null);
} else if (result.get() == buttonTypeNein) {
alert.close();
}
}

public void changeNotiz(CellEditEvent<?, ?> edittedCell) {
Details details = tableView.getSelectionModel().getSelectedItem();
if (testOnFirstCharacter(edittedCell.getNewValue().toString())) {
details.setBemerkung(edittedCell.getNewValue().toString());
Calendar calendar = Calendar.getInstance();

Timestamp timestamp = new Timestamp(calendar.getTimeInMillis());
details.setDate(timestamp);
connector.changeDetails(details);
colorFix(null);
initialize(null, null);
} else {
Alert alert = new Alert(AlertType.ERROR);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/application/resources/icons8-blockchain-technology-64.png"));
alert.setTitle("Eingabefehler");
alert.setHeaderText("Ups, ein Fehler ist aufgetreten");
alert.setContentText("Das erste Zeichen darf nicht leer sein.");
alert.show();
}
}

public boolean testOnFirstCharacter(String text) {
if (text.charAt(0) == ' ') {
return false;
}
return true;
}

public void buttonZurueck(ActionEvent event) throws IOException {
setGroupage(null);
setStudent(null);
setGroup(null);
setSemester(null);

sc.switchToZurueck(event);
}

public void colorFix(ActionEvent e) {
Platform.runLater(() -> {
tableView.setRowFactory(row -> new TableRow<Details>() {
@Override
public void updateItem(Details item, boolean empty) {
super.updateItem(item, empty);

if (item == null || empty) {
setStyle("");
} else {
// Now 'item' has all the info of the Person in this row
if (item.getBewertung() == 0) {
// We apply now the changes in all the cells of the row
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.BLACK);
getChildren().get(i).setStyle("-fx-background-color: #D8D8D8");
}
} else if (item.getBewertung() == 1) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #81F781");
}
} else if (item.getBewertung() == 2) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #F78181");
}
} else if (item.getBewertung() == 3) {
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: white");
}
}
}
}
});
});
}
}









share|improve this question















I want to color the rows of my tableview. But now it is that I need to click on the table or any other element first to get the tableView colored. I use Platform.runLater for adding, deleting and changing something.
For the initialize to get the colors even shown I need to do:



tableView.getColumns().get(3).setVisible(true);
tableView.getColumns().get(3).setVisible(false);

package application.controller.DetailsController;

import java.io.IOException;
import java.net.URL;
import java.sql.Timestamp;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.ArrayList;
import java.util.Calendar;
import application.Main;
import application.SceneSwitcher;
import application.DB.DBManager;
import application.models.*;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Labeled;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TableRow;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.StringConverter;

public class DetailsController implements Initializable { // Sascha

@FXML Label notierter;
@FXML TextField Notiz;
@FXML TextField filterField;
@FXML Button addDetails;
@FXML Button deleteDetails;
@FXML Button uebersichtSemester;
@FXML Button uebersichtGruppe;
@FXML Button uebersichtStudierende;
@FXML ComboBox<Details> Zuordnungsauswahl;

@FXML TableView<Details> tableView;
@FXML TableColumn<Details, String> IDColumn;
@FXML TableColumn<Details, String> NotizColumn;
@FXML TableColumn<Details, Timestamp> DatumColumn;
@FXML TableColumn<Details, Integer> BewertungColumn;

DBManager connector = Main.connector;
SceneSwitcher sc = new SceneSwitcher();
static Groupage groupage = null; // dürfen nicht initialsiert werden, sonst != null = setter aktiv
static Student student = null;
static Group group = null;
static Semester semester = null;

public static void setGroupage(Groupage g) {
groupage = g;
}

public static void setStudent(Student st) {
student = st;
}

public static void setGroup(Group gr) {
group = gr;
}

public static void setSemester(Semester se) {
semester = se;
}

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

// set up the columns in the table
IDColumn.setCellValueFactory(new PropertyValueFactory<Details, String>("id"));
NotizColumn.setCellValueFactory(new PropertyValueFactory<Details, String>("bemerkung"));
DatumColumn.setCellValueFactory(new PropertyValueFactory<Details, Timestamp>("date"));
DatumColumn.setCellFactory((TableColumn<Details, Timestamp> column) -> {
return new TableCell<Details, Timestamp>() {
@Override
protected void updateItem(Timestamp item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
} else {
setText(item.toLocalDateTime().format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss")));
}
}
};
});
BewertungColumn.setCellValueFactory(new PropertyValueFactory<Details, Integer>("bewertung"));
tableView.getColumns().get(3).setVisible(true);

tableView.setRowFactory(row -> new TableRow<Details>() {
@Override
public void updateItem(Details item, boolean empty) {
super.updateItem(item, empty);

if (item == null || empty) {
tableView.getColumns().get(3).setVisible(false);
setStyle("");
} else {
// Now 'item' has all the info of the Person in this row
if (item.getBewertung() == 0) {
// We apply now the changes in all the cells of the row
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.BLACK);
getChildren().get(i).setStyle("-fx-background-color: #D8D8D8");
}
} else if (item.getBewertung() == 1) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #81F781");
}
} else if (item.getBewertung() == 2) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #F78181");
}
} else if (item.getBewertung() == 3) {
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: white");
}
}
}


}
});


deleteDetails.setDisable(true);

if (groupage != null) {
tableView.setItems(getDetails());
notierter.setText(groupage.getBezeichnung());
} else if (student != null) {
tableView.setItems(getDetails());
notierter.setText(student.getVn() + " " + student.getNn());
} else if (group != null) {
tableView.setItems(getDetails());
notierter.setText(group.getBezeichnung());
} else if (semester != null) {
tableView.setItems(getDetails());
notierter.setText(semester.getBezeichnung());
}

tableView.setEditable(true);
IDColumn.setEditable(false);
NotizColumn.setCellFactory(TextFieldTableCell.forTableColumn());

// This will allow the table to select multiple rows at once
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

// ComboBox Implementierung
Zuordnungsauswahl.setItems(getDetailsForComboBox());
Zuordnungsauswahl.setConverter(new StringConverter<Details>() {

@Override
public String toString(Details object) {
if (object.getId() == 0) {
return "Normal";
} else if (object.getId() == 1) {
return "Gut";
} else if (object.getId() == 2) {
return "Schlecht";
} else {
return "Keine Zuordnung";
}
}

@Override
public Details fromString(String arg0) { // nur implementiert, weil es muss
return null;
}
});

FilteredList<Details> filteredData = new FilteredList<>(getDetails(), p -> true);

// 2. Set the filter Predicate whenever the filter changes.
filterField.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(details -> {
// If filter text is empty, display all persons.
if (newValue == null || newValue.isEmpty()) {
return true;
}

String lowerCaseFilter = newValue.toLowerCase();

if (details.getBemerkung().toLowerCase().contains(lowerCaseFilter)) {
return true;
}
return false;
});
});

// 3. Wrap the FilteredList in a SortedList.
SortedList<Details> sortedData = new SortedList<>(filteredData);

// 4. Bind the SortedList comparator to the TableView comparator.
sortedData.comparatorProperty().bind(tableView.comparatorProperty());

// 5. Add sorted (and filtered) data to the table.
tableView.setItems(sortedData);
}

public ObservableList<Details> getDetails() {
ObservableList<Details> details = FXCollections.observableArrayList();

if (groupage != null) {
List<Details> merge = connector.showDetailsAll(groupage);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
} else if (student != null) {
List<Details> merge = connector.showDetailsAll(student);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
} else if (group != null) {
List<Details> merge = connector.showDetailsAll(group);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
} else if (semester != null) {
List<Details> merge = connector.showDetailsAll(semester);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}
}

return details;
}

public ObservableList<Details> getDetailsForComboBox() {
ObservableList<Details> details = FXCollections.observableArrayList();
Details normal = new Details(0);
Details gut = new Details(1);
Details schlecht = new Details(2);
Details keineZuordnung = new Details(3);

List<Details> merge = new ArrayList<Details>();
merge.add(normal);
merge.add(gut);
merge.add(schlecht);
merge.add(keineZuordnung);

for (int i = 0; i < merge.size(); i++) {
details.add(merge.get(i));
}

return details;
}

public void userClickedOnTable() {
deleteDetails.setDisable(false);
}

public void buttonAddDetails() {
if (testOnFirstCharacter(Notiz.getText()) == false) {
Alert alert = new Alert(AlertType.ERROR);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/application/resources/icons8-blockchain-technology-64.png"));
alert.setTitle("Eingabefehler");
alert.setHeaderText("Ups, ein Fehler ist aufgetreten");
alert.setContentText("Das erste Zeichen darf nicht leer sein.");
alert.show();
} else {
Details det = new Details();

det.setGroupage(groupage);
det.setSemester(semester);
det.setGroup(group);
det.setStudent(student);
det.setBemerkung(Notiz.getText());
if (Zuordnungsauswahl.getValue() == null) {
det.setBewertung(3);
} else {
det.setBewertung(Zuordnungsauswahl.getValue().getId());
}

Calendar calendar = Calendar.getInstance();

Timestamp timestamp = new Timestamp(calendar.getTimeInMillis());

det.setDate(timestamp);

connector.addDetails(det);
colorFix(null);
initialize(null, null);
Notiz.clear();
}
}

public void buttonDeleteDetails() {
Alert alert = new Alert(AlertType.CONFIRMATION);

// Für das Icon im Alert
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/application/resources/icons8-blockchain-technology-64.png"));

alert.setTitle("Bestätigung erforderlich");
alert.setHeaderText("Soll diese Notiz wirklich gelöscht werden?");

ButtonType buttonTypeJa = new ButtonType("Ja");
ButtonType buttonTypeNein = new ButtonType("Nein");
ButtonType buttonTypeAbbrechen = new ButtonType("Abbrechen", ButtonData.CANCEL_CLOSE);

alert.getButtonTypes().setAll(buttonTypeJa, buttonTypeNein, buttonTypeAbbrechen);

Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeJa) {
Details det = tableView.getSelectionModel().getSelectedItem();
connector.deleteDetails(det);
colorFix(null);
initialize(null, null);
} else if (result.get() == buttonTypeNein) {
alert.close();
}
}

public void changeNotiz(CellEditEvent<?, ?> edittedCell) {
Details details = tableView.getSelectionModel().getSelectedItem();
if (testOnFirstCharacter(edittedCell.getNewValue().toString())) {
details.setBemerkung(edittedCell.getNewValue().toString());
Calendar calendar = Calendar.getInstance();

Timestamp timestamp = new Timestamp(calendar.getTimeInMillis());
details.setDate(timestamp);
connector.changeDetails(details);
colorFix(null);
initialize(null, null);
} else {
Alert alert = new Alert(AlertType.ERROR);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image("/application/resources/icons8-blockchain-technology-64.png"));
alert.setTitle("Eingabefehler");
alert.setHeaderText("Ups, ein Fehler ist aufgetreten");
alert.setContentText("Das erste Zeichen darf nicht leer sein.");
alert.show();
}
}

public boolean testOnFirstCharacter(String text) {
if (text.charAt(0) == ' ') {
return false;
}
return true;
}

public void buttonZurueck(ActionEvent event) throws IOException {
setGroupage(null);
setStudent(null);
setGroup(null);
setSemester(null);

sc.switchToZurueck(event);
}

public void colorFix(ActionEvent e) {
Platform.runLater(() -> {
tableView.setRowFactory(row -> new TableRow<Details>() {
@Override
public void updateItem(Details item, boolean empty) {
super.updateItem(item, empty);

if (item == null || empty) {
setStyle("");
} else {
// Now 'item' has all the info of the Person in this row
if (item.getBewertung() == 0) {
// We apply now the changes in all the cells of the row
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.BLACK);
getChildren().get(i).setStyle("-fx-background-color: #D8D8D8");
}
} else if (item.getBewertung() == 1) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #81F781");
}
} else if (item.getBewertung() == 2) {
for (int i = 0; i < getChildren().size(); i++) {
// ((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: #F78181");
}
} else if (item.getBewertung() == 3) {
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setTextFill(Color.RED);
getChildren().get(i).setStyle("-fx-background-color: white");
}
}
}
}
});
});
}
}






javafx tableview tablerow






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 at 19:16









Federico Grandi

2,45811026




2,45811026










asked Nov 22 at 13:01









CptDayDreamer

62




62








  • 1




    Please try to write a minimal, complete and verifiable example : stackoverflow.com/help/mcve
    – Calips
    Nov 22 at 13:48










  • unrelated to your problem: please learn java naming conventions and stick to them
    – kleopatra
    Nov 22 at 14:22










  • related, though only general advice (as long as your example it's neither minimal nor standalone, I wont give it a closer look, sry) : a) if you need setVisible(false)/(true) there's something wrong in your setup b) there have been several QAs recently related to conditional row styles, please search the site and apply what you learn from the answers
    – kleopatra
    Nov 22 at 14:26












  • I researched like the whole stackOverflow and even my teacher at the university couldn't figure out the problem. Of course I need setVisible when I use the updateItem method.
    – CptDayDreamer
    Nov 22 at 14:32










  • Hi, welcome to Stack Overflow! I've removed the redundant tag from your title, and also removed the blockquote at the end of the post ;)
    – Federico Grandi
    Nov 22 at 19:16














  • 1




    Please try to write a minimal, complete and verifiable example : stackoverflow.com/help/mcve
    – Calips
    Nov 22 at 13:48










  • unrelated to your problem: please learn java naming conventions and stick to them
    – kleopatra
    Nov 22 at 14:22










  • related, though only general advice (as long as your example it's neither minimal nor standalone, I wont give it a closer look, sry) : a) if you need setVisible(false)/(true) there's something wrong in your setup b) there have been several QAs recently related to conditional row styles, please search the site and apply what you learn from the answers
    – kleopatra
    Nov 22 at 14:26












  • I researched like the whole stackOverflow and even my teacher at the university couldn't figure out the problem. Of course I need setVisible when I use the updateItem method.
    – CptDayDreamer
    Nov 22 at 14:32










  • Hi, welcome to Stack Overflow! I've removed the redundant tag from your title, and also removed the blockquote at the end of the post ;)
    – Federico Grandi
    Nov 22 at 19:16








1




1




Please try to write a minimal, complete and verifiable example : stackoverflow.com/help/mcve
– Calips
Nov 22 at 13:48




Please try to write a minimal, complete and verifiable example : stackoverflow.com/help/mcve
– Calips
Nov 22 at 13:48












unrelated to your problem: please learn java naming conventions and stick to them
– kleopatra
Nov 22 at 14:22




unrelated to your problem: please learn java naming conventions and stick to them
– kleopatra
Nov 22 at 14:22












related, though only general advice (as long as your example it's neither minimal nor standalone, I wont give it a closer look, sry) : a) if you need setVisible(false)/(true) there's something wrong in your setup b) there have been several QAs recently related to conditional row styles, please search the site and apply what you learn from the answers
– kleopatra
Nov 22 at 14:26






related, though only general advice (as long as your example it's neither minimal nor standalone, I wont give it a closer look, sry) : a) if you need setVisible(false)/(true) there's something wrong in your setup b) there have been several QAs recently related to conditional row styles, please search the site and apply what you learn from the answers
– kleopatra
Nov 22 at 14:26














I researched like the whole stackOverflow and even my teacher at the university couldn't figure out the problem. Of course I need setVisible when I use the updateItem method.
– CptDayDreamer
Nov 22 at 14:32




I researched like the whole stackOverflow and even my teacher at the university couldn't figure out the problem. Of course I need setVisible when I use the updateItem method.
– CptDayDreamer
Nov 22 at 14:32












Hi, welcome to Stack Overflow! I've removed the redundant tag from your title, and also removed the blockquote at the end of the post ;)
– Federico Grandi
Nov 22 at 19:16




Hi, welcome to Stack Overflow! I've removed the redundant tag from your title, and also removed the blockquote at the end of the post ;)
– Federico Grandi
Nov 22 at 19:16

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53431624%2fcoloring-rows-in-tableview%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53431624%2fcoloring-rows-in-tableview%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

What visual should I use to simply compare current year value vs last year in Power BI desktop

How to ignore python UserWarning in pytest?

Alexandru Averescu