gpt4 book ai didi

java - 如何根据输入突出显示 JavaFX TableView 中的特定字符

转载 作者:行者123 更新时间:2023-12-02 09:17:46 24 4
gpt4 key购买 nike

我有一个 JavaFx TableView,其中填充了 FilteredList 中的数据和用于在列表中执行搜索的搜索字段。我想根据搜索字段中的数据动态突出显示表中的字符。我怎样才能做到这一点?

最佳答案

这可以通过提供Text来完成细胞工厂中的物体。它使事情变得更加复杂,因为您的表列值需要提供更多信息,而不仅仅是字符串或数字。

我将通过创建一个类来表示每个单元格文本的一部分(无论是否是匹配的一部分)来实现此目的:

public class TextSegment {
private final boolean match;
private final String text;

public TextSegment(String text,
boolean isMatch) {

this.text = Objects.requireNonNull(text, "Text cannot be null.");
this.match = isMatch;
}

public String getText() {
return text;
}

public boolean isMatch() {
return match;
}

@Override
public String toString() {
return "Segment[match=" + match + " \"" + text + "\"]";
}

public static List<TextSegment> search(String text,
String searchText,
boolean caseSensitive) {

if (text == null || text.isBlank() ||
searchText == null || searchText.isBlank()) {

return Collections.singletonList(new TextSegment(text, false));
}

List<TextSegment> segments = new ArrayList<>();

Pattern pattern = Pattern.compile(Pattern.quote(searchText),
caseSensitive ? 0 : Pattern.CASE_INSENSITIVE);

int lastEnd = 0;
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
int start = matcher.start();
if (start > lastEnd) {
segments.add(new TextSegment(
text.substring(lastEnd, start), false));
}
segments.add(new TextSegment(matcher.group(), true));
lastEnd = matcher.end();
}

String tail = text.substring(lastEnd);
if (!tail.isEmpty()) {
segments.add(new TextSegment(tail, false));
}

return segments;
}
}

在表中保存一行数据的类需要一个附加属性,该属性以上述类型的实例列表的形式保存数据:

private final StringProperty name;
private final ListProperty<TextSegment> nameMatches;

// ...

public StringProperty nameProperty() {
return name;
}

public ListProperty<TextSegment> nameMatchesProperty() {
return nameMatches;
}

然后,在构造函数中将它们链接在一起:

this.name.addListener(
(o, old, newName) -> nameMatches.setAll(TextSegment.search(newName,
getSearchText(), isCaseSensitive())));

TableColumn 将定义为:

TableColumn<RowItem, ObservableList<TextSegment>> nameColumn =
new TableColumn<>("Name");

nameColumn.setCellValueFactory(
f -> f.getValue().nameMatchesProperty());

最后,一系列 TextSegment 的显示可以作为 Text 节点的相邻列表来完成:

nameColumn.setCellFactory(c -> new SearchableCell<>());

其中 SearchableCell 是一个通过下划线显示匹配文本的类:

public class SearchableCell<S, T extends Iterable<TextSegment>>
extends TableCell<S, T> {
@Override
protected void updateItem(T item,
boolean empty) {
super.updateItem(item, empty);

setText(null);
if (empty || item == null) {
setGraphic(null);
} else {
HBox row = new HBox();
row.setAlignment(Pos.BASELINE_LEFT);
for (TextSegment segment : item) {
Text text = new Text(segment.getText());
text.setUnderline(segment.isMatch());
row.getChildren().add(text);
}
setGraphic(row);
}
}
}

这是一个将所有内容组合在一起的示例:

import java.text.NumberFormat;

import java.util.Objects;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

import javafx.application.Application;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.SimpleListProperty;

import javafx.collections.ObservableList;
import javafx.collections.FXCollections;

import javafx.geometry.Insets;
import javafx.geometry.Pos;

import javafx.stage.Stage;

import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;

public class TableHighlight
extends Application {
static class TextSegment {
private final boolean match;
private final String text;

public TextSegment(String text,
boolean isMatch) {

this.text = Objects.requireNonNull(text, "Text cannot be null.");
this.match = isMatch;
}

public String getText() {
return text;
}

public boolean isMatch() {
return match;
}

@Override
public String toString() {
return "Segment[match=" + match + " \"" + text + "\"]";
}

public static List<TextSegment> search(String text,
String searchText,
boolean caseSensitive) {

if (text == null || text.isBlank() ||
searchText == null || searchText.isBlank()) {

return Collections.singletonList(new TextSegment(text, false));
}

List<TextSegment> segments = new ArrayList<>();

Pattern pattern = Pattern.compile(Pattern.quote(searchText),
caseSensitive ? 0 : Pattern.CASE_INSENSITIVE);

int lastEnd = 0;
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
int start = matcher.start();
if (start > lastEnd) {
segments.add(new TextSegment(
text.substring(lastEnd, start), false));
}
segments.add(new TextSegment(matcher.group(), true));
lastEnd = matcher.end();
}

String tail = text.substring(lastEnd);
if (!tail.isEmpty()) {
segments.add(new TextSegment(tail, false));
}

return segments;
}
}

static class StateInfo {
private final StringProperty name;
private final StringProperty abbreviation;
private final StringProperty capital;
private final IntegerProperty population;

private final ListProperty<TextSegment> nameMatches;
private final ListProperty<TextSegment> abbreviationMatches;
private final ListProperty<TextSegment> capitalMatches;

private final StringProperty searchText;
private final BooleanProperty caseSensitive;

public StateInfo() {
this(null, null, null, 0);
}

public StateInfo(String name,
String abbreviation,
String capital,
int population) {

this.name = new SimpleStringProperty(this, "name",
name);
this.abbreviation = new SimpleStringProperty(this, "abbreviation",
abbreviation);
this.capital = new SimpleStringProperty(this, "capital",
capital);
this.population = new SimpleIntegerProperty(this, "population",
population);

searchText = new SimpleStringProperty(this, "searchText");
caseSensitive = new SimpleBooleanProperty(this, "caseSensitive");

nameMatches = new SimpleListProperty<>(this,
"nameMatches", FXCollections.observableArrayList());
abbreviationMatches = new SimpleListProperty<>(this,
"abbreviationMatches", FXCollections.observableArrayList());
capitalMatches = new SimpleListProperty<>(this,
"capitalMatches", FXCollections.observableArrayList());

this.name.addListener(
(o, old, newName) -> update(nameMatches, newName));
this.abbreviation.addListener(
(o, old, newAbbr) -> update(abbreviationMatches, newAbbr));
this.capital.addListener(
(o, old, newCapital) -> update(capitalMatches, newCapital));

searchText.addListener(o -> updateAllMatches());
caseSensitive.addListener(o -> updateAllMatches());

updateAllMatches();
}

private void update(ObservableList<TextSegment> segments,
String text) {

segments.setAll(TextSegment.search(text,
getSearchText(), isCaseSensitive()));
}

private void updateAllMatches() {
update(nameMatches, getName());
update(abbreviationMatches, getAbbreviation());
update(capitalMatches, getCapital());
}

public StringProperty nameProperty() { return name; }
public String getName() { return name.get(); }
public void setName(String name) { this.name.set(name); }

public StringProperty abbreviationProperty() { return abbreviation; }
public String getAbbreviation() { return abbreviation.get(); }
public void setAbbreviation(String abbr) { this.abbreviation.set(abbr); }

public StringProperty capitalProperty() { return capital; }
public String getCapital() { return capital.get(); }
public void setCapital(String capital) { this.capital.set(capital); }

public IntegerProperty populationProperty() { return population; }
public int getPopulation() { return population.get(); }
public void setPopulation(int population) { this.population.set(population); }

public StringProperty searchTextProperty() { return searchText; }
public String getSearchText() { return searchText.get(); }
public void setSearchText(String searchText) { this.searchText.set(searchText); }

public BooleanProperty caseSensitiveProperty() { return caseSensitive; }
public boolean isCaseSensitive() { return caseSensitive.get(); }
public void setCaseSensitive(boolean c) { caseSensitive.set(c); }

public ListProperty<TextSegment> nameMatchesProperty() {
return nameMatches;
}
public ObservableList<TextSegment> getNameMatches() {
return nameMatches.get();
}
public void setNameMatches(ObservableList<TextSegment> list) {
nameMatches.set(list);
}

public ListProperty<TextSegment> abbreviationMatchesProperty() {
return abbreviationMatches;
}
public ObservableList<TextSegment> getAbbreviationMatches() {
return abbreviationMatches.get();
}
public void setAbbreviationMatches(ObservableList<TextSegment> list) {
abbreviationMatches.set(list);
}

public ListProperty<TextSegment> capitalMatchesProperty() {
return capitalMatches;
}
public ObservableList<TextSegment> getCapitalMatches() {
return capitalMatches.get();
}
public void setCapitalMatches(ObservableList<TextSegment> list) {
capitalMatches.set(list);
}

@Override
public String toString() {
return String.format("%s[name=%s abbr=%s capital=%s pop=%,d]",
getName(), getAbbreviation(), getCapital(), getPopulation());
}
}

static class SearchableCell<S, T extends Iterable<TextSegment>>
extends TableCell<S, T> {
@Override
protected void updateItem(T item,
boolean empty) {
super.updateItem(item, empty);

setText(null);
if (empty || item == null) {
setGraphic(null);
} else {
HBox row = new HBox();
row.setAlignment(Pos.BASELINE_LEFT);
for (TextSegment segment : item) {
Text text = new Text(segment.getText());
text.setUnderline(segment.isMatch());
row.getChildren().add(text);
}
setGraphic(row);
}
}
}

static class NumberCell<S, T extends Number>
extends TableCell<S, T> {
private final NumberFormat format = NumberFormat.getInstance();

@Override
protected void updateItem(T item, boolean empty) {
super.updateItem(item, empty);

setGraphic(null);
if (empty || item == null) {
setText(null);
} else {
setText(format.format(item));
}
}
}

@Override
public void start(Stage stage) {
TableView<StateInfo> table = new TableView<>();

TableColumn<StateInfo, ObservableList<TextSegment>> nameColumn =
new TableColumn<>("Name");
TableColumn<StateInfo, ObservableList<TextSegment>> abbreviationColumn =
new TableColumn<>("Abbreviation");
TableColumn<StateInfo, ObservableList<TextSegment>> capitalColumn =
new TableColumn<>("Capital");
TableColumn<StateInfo, Number> populationColumn =
new TableColumn<>("Population");

table.getColumns().add(nameColumn);
table.getColumns().add(abbreviationColumn);
table.getColumns().add(capitalColumn);
table.getColumns().add(populationColumn);

nameColumn.setCellValueFactory(
f -> f.getValue().nameMatchesProperty());
abbreviationColumn.setCellValueFactory(
f -> f.getValue().abbreviationMatchesProperty());
capitalColumn.setCellValueFactory(
f -> f.getValue().capitalMatchesProperty());
populationColumn.setCellValueFactory(
f -> f.getValue().populationProperty());

nameColumn.setCellFactory(c -> new SearchableCell<>());
abbreviationColumn.setCellFactory(c -> new SearchableCell<>());
capitalColumn.setCellFactory(c -> new SearchableCell<>());
populationColumn.setCellFactory(c -> new NumberCell<>());

table.getItems().setAll(createData());

TextField searchField = new TextField();
searchField.textProperty().addListener((o, old, text) ->
table.getItems().forEach(s -> s.setSearchText(text)));

CheckBox caseSensitiveButton = new CheckBox("Case sensitive");
caseSensitiveButton.selectedProperty().addListener((o, old, selected) ->
table.getItems().forEach(s -> s.setCaseSensitive(selected)));

Label searchLabel = new Label("Search for: ");
searchLabel.setLabelFor(searchField);

HBox searchFields = new HBox(
searchLabel, searchField, caseSensitiveButton);
searchFields.setAlignment(Pos.BASELINE_LEFT);
HBox.setMargin(caseSensitiveButton, new Insets(0, 0, 0, 24));

searchFields.setPadding(new Insets(6, 6, 12, 6));

Scene scene = new Scene(
new BorderPane(table, searchFields, null, null, null));

stage.setScene(scene);
stage.setTitle("Table Search");
stage.show();
}

private static Collection<StateInfo> createData() {
return Arrays.asList(
new StateInfo("Alabama", "AL", "Montgomery", 543097),
new StateInfo("Alaska", "AK", "Juneau", 245813),
new StateInfo("Arizona", "AZ", "Phoenix", 651968),
new StateInfo("Arkansas", "AR", "Little Rock", 502304),
new StateInfo("California", "CA", "Sacramento", 719219),
new StateInfo("Colorado", "CO", "Denver", 632840),
new StateInfo("Connecticut", "CT", "Hartford", 510381),
new StateInfo("Delaware", "DE", "Dover", 322390),
new StateInfo("Florida", "FL", "Tallahassee", 734459),
new StateInfo("Georgia", "GA", "Atlanta", 657467),
new StateInfo("Hawaii", "HI", "Honolulu", 355123),
new StateInfo("Idaho", "ID", "Boise", 438552),
new StateInfo("Illinois", "IL", "Springfield", 637054),
new StateInfo("Indiana", "IN", "Indianapolis", 608353),
new StateInfo("Iowa", "IA", "Des Moines", 526024),
new StateInfo("Kansas", "KS", "Topeka", 485251),
new StateInfo("Kentucky", "KY", "Frankfort", 558550),
new StateInfo("Louisiana", "LA", "Baton Rouge", 582497),
new StateInfo("Maine", "ME", "Augusta", 334601),
new StateInfo("Maryland", "MD", "Annapolis", 604272),
new StateInfo("Massachusetts", "MA", "Boston", 627468),
new StateInfo("Michigan", "MI", "Lansing", 624735),
new StateInfo("Minnesota", "MN", "Saint Paul", 561118),
new StateInfo("Mississippi", "MS", "Jackson", 497755),
new StateInfo("Missouri", "MO", "Jefferson City", 612645),
new StateInfo("Montana", "MT", "Helena", 354102),
new StateInfo("Nebraska", "NE", "Lincoln", 385854),
new StateInfo("Nevada", "NV", "Carson City", 505732),
new StateInfo("New Hampshire", "NH", "Concord", 339115),
new StateInfo("New Jersey", "NJ", "Trenton", 636323),
new StateInfo("New Mexico", "NM", "Santa Fe", 419086),
new StateInfo("New York", "NY", "Albany", 673869),
new StateInfo("North Carolina", "NC", "Raleigh", 692241),
new StateInfo("North Dakota", "ND", "Bismarck", 253359),
new StateInfo("Ohio", "OH", "Columbus", 649413),
new StateInfo("Oklahoma", "OK", "Oklahoma City", 563297),
new StateInfo("Oregon", "OR", "Salem", 598673),
new StateInfo("Pennsylvania", "PA", "Harrisburg", 640353),
new StateInfo("Rhode Island", "RI", "Providence", 264329),
new StateInfo("South Carolina", "SC", "Columbia", 564903),
new StateInfo("South Dakota", "SD", "Pierre", 294078),
new StateInfo("Tennessee", "TN", "Nashville", 615455),
new StateInfo("Texas", "TX", "Austin", 755312),
new StateInfo("Utah", "UT", "Salt Lake City", 526851),
new StateInfo("Vermont", "VT", "Montpelier", 208766),
new StateInfo("Virginia", "VA", "Richmond", 655207),
new StateInfo("Washington", "WA", "Olympia", 627966),
new StateInfo("West Virginia", "WV", "Charleston", 361166),
new StateInfo("Wisconsin", "WI", "Madison", 581357),
new StateInfo("Wyoming", "WY", "Cheyenne", 192579)
);
}

public static class Main {
public static void main(String[] args) {
Application.launch(TableHighlight.class, args);
}
}
}

关于java - 如何根据输入突出显示 JavaFX TableView 中的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58878989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com