I am developing chat application in java and using JavaFX for the development of GUI. I got problem while displaying message in custom ListView
. I used setcellfactory
to set value in custom listview.
When I set value to ListView
statically it works fine. But when I set value to the listview dynamically through an ObservableList
, it repeats cell for same value in list
Here is my code:
package sample;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.util.Callback;
import javax.swing.*;
import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML
public Button send;
@FXML
public Label botName;
@FXML
public TextField message;
@FXML
public ListView<String> oldMessage, botList;
@FXML
public ListView<String> chatWindow;
ObservableList<String> items, chatcontent;
@Override
public void initialize(URL location, ResourceBundle resources) {
File file = new File("C:\\ab\\bots");
String[] names = file.list();
items = FXCollections.observableArrayList(names);
oldMessage.setItems(items);
botList.setItems(items);
//default selection
botList.getSelectionModel().select(0);
botName.setText(botList.getSelectionModel().selectedItemProperty().getValue());
botList.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
botName.setText(newValue);
}
});
botList.setCellFactory(new Callback<ListView<String>, javafx.scene.control.ListCell<String>>() {
@Override
public ListCell<String> call(ListView<String> listView) {
return new ListViewCell();
}
});
//send message
message.setOnAction(e -> {
String c = message.getText().toString();
chatcontent.add(c);
chatWindow.scrollTo(c);
chatWindow.refresh();
message.clear();
});
send.setOnAction(e -> {
String c = message.getText().toString();
chatcontent.add(c);
chatWindow.scrollTo(c);
chatWindow.refresh();
message.clear();
});
setListView();
}
public void setListView() {
chatcontent = FXCollections.observableArrayList(items);
chatWindow.setItems(chatcontent);
chatWindow.setCellFactory(new Callback<ListView<String>, javafx.scene.control.ListCell<String>>() {
@Override
public ListCell<String> call(ListView<String> listView) {
return new ListViewCellChat();
}
});
}
static class ListViewCellChat extends ListCell<String> {
@Override
public void updateItem(String string, boolean empty) {
super.updateItem(string, empty);
if (string != null) {
Data1 data = new Data1();
data.setInfo(string);
setGraphic(data.getBox());
}
}
}
}