我有一个名为tablesettings的表视图(@FXML TableView tablesettings)
我有textfield从tableview搜索值。
但我想在tableview上更改已分隔匹配文本的字体颜色。
简单代码
String sDriverName = "org.sqlite.JDBC";
try {
Class.forName(sDriverName);
String sTempDb = "systemnet.db";
String sJdbc = "jdbc:sqlite";
String sDbUrl = sJdbc + ":" + sTempDb;
// create a database connection
Connection conn = DriverManager.getConnection(sDbUrl);
try {
Statement stmt = conn.createStatement();
try {
try {
connected();
data = FXCollections.observableArrayList();
ResultSet rs = stmt.executeQuery("SELECT * from Belgiler");
while (rs.next()) {
data.add(new form1Controller.userdata(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4)));
}
cid.setCellValueFactory(new PropertyValueFactory("id"));
ctwo.setCellValueFactory(new PropertyValueFactory("two"));
csec.setCellValueFactory(new PropertyValueFactory("sec"));
ctri.setCellValueFactory(new PropertyValueFactory("tri"));
tablesettings.setItems(null);
tablesettings.setItems(data);
tablesettings.setEditable(true);
closed();
} catch (Exception e) {System.out.println("Error on Building Data"+ e.toString());
}
} finally {
try { stmt.close(); } catch (Exception ignore) {}
}
} finally {
try { conn.close(); } catch (Exception ignore) {}
}
} catch (Exception ex) {
Logger.getLogger(form1Controller.class.getName()).log(Level.SEVERE, null, ex);
}
FilteredList<userdata> filt = new FilteredList<>(data, p ->true);
textfield1.textProperty().addListener((observable, oldValue, newValue) -> {
filt.setPredicate(userdata -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if (userdata.two.toString().toLowerCase().contains(lowerCaseFilter)) {
return true; // change font color
} else if (userdata.sec.toString().toLowerCase().contains(lowerCaseFilter)) {
return true;
}
return false; // Does not match.
});SortedList<userdata> sortedData = new SortedList<>(filt);
sortedData.comparatorProperty().bind(tablesettings.comparatorProperty());
tablesettings.setItems(sortedData);
});
答案 0 :(得分:0)
使用观察搜索文本属性的自定义TableCell
,并使用TextFlow
作为其图形而不是纯文本。当搜索文本属性发生更改时,或者从updateItem(...)
方法更改时,在项目中查找搜索文本的出现位置,并从块中构建文本流,以便突出显示相应的块。
这是一个只突出显示文本第一次出现的简单示例;您可以修改它以突出显示所有匹配项:
import javafx.beans.value.ObservableValue;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
public class HighlightingTableCell<S> extends TableCell<S, String> {
private final ObservableValue<String> highlightText ;
private final TextFlow textFlow ;
public HighlightingTableCell(ObservableValue<String> highlightText) {
this.highlightText = highlightText ;
this.textFlow = new TextFlow() ;
textFlow.setPrefHeight(12);
highlightText.addListener((obs, oldText, newText) -> {
updateTextFlow(newText);
});
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
updateTextFlow(highlightText.getValue());
setGraphic(textFlow);
}
}
private void updateTextFlow(String highlight) {
if (isEmpty()) {
return ;
}
String item = getItem();
int index = item.indexOf(highlight);
if (highlight.isEmpty() || index < 0) {
Text text = new Text(item);
textFlow.getChildren().setAll(text);
return ;
}
Text prior = new Text(item.substring(0, index));
Text highlighted = new Text(item.substring(index, index+highlight.length()));
highlighted.getStyleClass().add("highlight");
Text post = new Text(item.substring(index+highlight.length()));
textFlow.getChildren().setAll(prior, highlighted, post);
}
}
这是一个快速测试案例:
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class HighlightingFilteredTable extends Application {
@Override
public void start(Stage primaryStage) {
TableView<Person> table = new TableView<>();
TextField searchField = new TextField();
searchField.setPromptText("Enter filter text");
TableColumn<Person, String> firstNameColumn = new TableColumn<>("First Name");
firstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
firstNameColumn.setCellFactory(tc -> new HighlightingTableCell<>(searchField.textProperty()));
TableColumn<Person, String> lastNameColumn = new TableColumn<>("Last Name");
lastNameColumn.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
lastNameColumn.setCellFactory(tc -> new HighlightingTableCell<>(searchField.textProperty()));
table.getColumns().add(firstNameColumn);
table.getColumns().add(lastNameColumn);
ObservableList<Person> allData= FXCollections.observableArrayList(
new Person("Jacob", "Smith"),
new Person("Isabella", "Johnson"),
new Person("Ethan", "Williams"),
new Person("Emma", "Jones"),
new Person("Michael", "Brown")
);
FilteredList<Person> filteredList = new FilteredList<>(allData);
filteredList.predicateProperty().bind(Bindings.createObjectBinding(() ->
person -> person.getFirstName().contains(searchField.getText()) || person.getLastName().contains(searchField.getText()),
searchField.textProperty()));
table.setItems(filteredList);
BorderPane.setMargin(searchField, new Insets(5));
BorderPane root = new BorderPane(table,searchField, null, null, null);
Scene scene = new Scene(root);
scene.getStylesheets().add("style.css");
primaryStage.setScene(scene);
primaryStage.show();
}
public static class Person {
private final StringProperty firstName = new SimpleStringProperty();
private final StringProperty lastName = new SimpleStringProperty();
public Person(String firstName, String lastName) {
setFirstName(firstName);
setLastName(lastName);
}
public final StringProperty firstNameProperty() {
return this.firstName;
}
public final String getFirstName() {
return this.firstNameProperty().get();
}
public final void setFirstName(final String firstName) {
this.firstNameProperty().set(firstName);
}
public final StringProperty lastNameProperty() {
return this.lastName;
}
public final String getLastName() {
return this.lastNameProperty().get();
}
public final void setLastName(final String lastName) {
this.lastNameProperty().set(lastName);
}
}
public static void main(String[] args) {
launch(args);
}
}
使用style.css:
.table-cell .highlight {
-fx-fill: red ;
}