I'm building a chat app using JavaFX. Now for chat messages display, I use a simple ListView of ChatItems with a custom cell factory, ChatCell.
ChatItem could be a ChatLabel (server announcements, status change, etc), or a ChatMessage (message sent by self or other parties). And ChatMessage could be extended to show various content (just ChatTextMessage and ChatImageMessage for now)
My custom cell checks the type/characteristics of the item and provides the proper view accordingly.
I'd like to show a timestamp on each ChatMessage view on bottom right corner of the chat bubble. BUT if the text is only one line, I want the timestamp to show on an extra space on the right of the text. (kinda like WhatsApp chat or most chat apps).
Here's a demo:
My current implementation (shown in the demo) uses a boolean property in ChatMessage that determines if the view should be multiline or not. It checks it on every update. I also add a listener to ListView width and call refresh() when it changes. All of this seems excessive. And I don't think adding a "view-related" property to a "model" is a good design. Not to mention that on the first item update, the timestamp is not at the correct place for some reason.
How can I do this properly?
UPDATE 1:
I added a property extractor for the ListView items, and added a listener for the ListView width that calls updateItem on width changes. Now I don't have to call refresh()
Here is ChatCell class:
public class ChatCell extends ListCell<ChatItem> {
private ChatItemView view;
private InvalidationListener listViewListener;
private InvalidationListener listViewWidthListener;
public ChatCell() {
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
listViewWidthListener = e -> {
updateItem(getItem(), isEmpty());
};
listViewListener = e -> {
if(getView() == null) return;
getView().unbindWidth();
if(listViewProperty().get() != null) {
getView().bindWidth(listViewProperty().get().widthProperty());
listViewProperty().get().widthProperty().addListener(listViewWidthListener);
listViewWidthListener.invalidated(listViewProperty().get().widthProperty());
}
};
}
public ChatItemView getView() {
return view;
}
private void initChatLabelView() {
view = new ChatLabelView();
}
private void initChatMessageView(ChatMessage message) {
view = new ChatMessageViewWrapper(message);
}
private void resetView() {
if(view == null) return;
view.unbindWidth();
listViewProperty().removeListener(listViewListener);
if(getListView() != null)
getListView().widthProperty().removeListener(listViewWidthListener);
view = null;
}
private void newViewCreated() {
listViewProperty().addListener(listViewListener);
setGraphic(view);
listViewListener.invalidated(listViewProperty());
}
#Override
protected void updateItem(ChatItem item, boolean empty) {
super.updateItem(item, empty);
if(item == null || empty) {
setGraphic(null);
setText(null);
resetView();
} else {
// First-level comparison: Label vs. Message
if(item.getViewType() == ViewType.LABEL) {
if(view == null || !(view instanceof ChatLabelView)) {
resetView();
initChatLabelView();
newViewCreated();
}
}
else if(item.getViewType() == ViewType.MESSAGE) {
ChatMessage message = (ChatMessage) item;
if(view == null || !(view instanceof ChatMessageViewWrapper)) {
resetView();
initChatMessageView(message);
newViewCreated();
}
else {
ChatMessageViewWrapper bubble = (ChatMessageViewWrapper) view;
// Second-level comparison: Self-message vs. other user message,
// Text vs. Image (or file), multiline vs. oneline
if( (bubble.getContentType() != message.getContentType())
|| (bubble.isSelf() ^ message.isSelf())
|| (bubble.isMultiline() ^ message.isMultiline())) {
resetView();
initChatMessageView(message);
newViewCreated();
}
}
}
else {
return;
}
view.setItem(item);
}
}
#Override
public Orientation getContentBias() {
return Orientation.HORIZONTAL;
}
}
Related
I am trying to create custom cells in a ListView , but every time I add a new item, the updateItem(TextFlow item, Boolean empty) is executed twice: one time it receives null and true, and the second time it does not (!null and false)
If I do not implement the setCellFactory method, then I can add the items to the table without problems.
ListView without custom cellFactory
However, when I do implement it, it simply creates 10 empty cells (where is the content?).
ListView with custom cellFactory
public class Controller implements Initializable {
#FXML
private ListView <TextFlow> console;
private ObservableList<TextFlow> data = FXCollections.observableArrayList();
public void initialize(URL location, ResourceBundle resources) {
console.setCellFactory(new Callback<ListView<TextFlow>, ListCell<TextFlow>>() {
#Override
public ListCell<TextFlow> call(ListView<TextFlow> param) {
return new ListCell<TextFlow>() {
#Override
protected void updateItem(TextFlow item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setItem(item);
setStyle("-fx-control-inner-background: blue;");
} else {
System.out.println("Item is null.");
}
}
};
}
});
for (int i = 0 ; i < 10; i++) {
Text txt = getStyledText("This is item number " + i + ".");
TextFlow textFlow = new TextFlow();
textFlow.getChildren().add(txt);
data.add(textFlow);
}
console.setItems(data);
}
private Text getStyledText (String inputText) {
Text text = new Text(inputText);
text.setFont(new Font("Courier New",12));
text.setFill(Paint.valueOf("#000000"));
return text;
}
}
updateItem can be called an arbitrary amount of times, different items may be passed and the cell can go from empty to non-empty and the other way round. ListView creates about as many cells as you see on screen and fills them with items. E.g. scrolling or modifications of the items list or resizing of the ListView can result in updates.
For this reason any cell needs to be able to deal with an arbitrary sequence of items (or null+empty) being passed to the updateItem method.
Furthermore you should avoid invoking setItem yourself, since super.updateItem does that already. Use setGraphic instead, if you want to display the item in the cell:
#Override
public ListCell<TextFlow> call(ListView<TextFlow> param) {
return new ListCell<TextFlow>() {
#Override
protected void updateItem(TextFlow item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setStyle("-fx-control-inner-background: blue;");
setGraphic(item);
} else {
setStyle(null);
setGraphic(null);
System.out.println("Item is null.");
}
}
};
}
There TreeView, each element of which implements Viewable interface:
public interface Viewable {
enum ViewStyle {
NEW("-fx-background-color: b8faa7;"),
NEW_PARENT("-fx-background-color: b8ebbb;"),
LOCKED("-fx-background-color: adadad; "),
HAS_NO_DATA("-fx-background-color: eb8d8d;");
String style;
ViewStyle(String style){
this.style = style;
}
public String getStyle() {
return style;
}
}
ViewStyle getViewStyle();
void setViewStyle(ViewStyle style);
StringProperty styleProperty();
String getTreeItemTitle();
void setTreeItemTitle(String title);
StringProperty titleProperty();
}
Each element has its own .styleProperty(), and get value from ViewStyle.getStyle()
This property bind for each TreeCell.styleProperty():
treeView.setCellFactory(new Callback<TreeView<Viewable>, TreeCell<Viewable>>() {
#Override
public TreeCell<Viewable> call(TreeView<Viewable> param) {
return new TreeCell<Viewable>() {
#Override
protected void updateItem(Viewable item, boolean empty) {
textProperty().unbind();
styleProperty().unbind();
if (empty || item == null) {
setGraphic(null);
textProperty().set(null);
styleProperty().set(null);
return;
}
if (item != null) {
styleProperty().bind(item.styleProperty());
textProperty().bind(item.titleProperty());
}
super.updateItem(item, empty);
}
};
}
});
The problem is that tree cells are displayed ugly in the selection. That is the color of the selected cell does not change. Changing only the color of the letters (in accordance with the default theme), but it is not very convenient. Therefore, probably it is necessary to attach .css files. At the same time, I don't understand how to change the style (default and when selected) of the cell depending on the current ViewStyle.
You could simply change the css property to one that is only used for unselected cells (-fx-control-inner-background):
enum ViewStyle {
NEW("-fx-control-inner-background: b8faa7;"),
NEW_PARENT("-fx-control-inner-background: b8ebbb;"),
LOCKED("-fx-control-inner-background: adadad; "),
HAS_NO_DATA("-fx-control-inner-background: eb8d8d;");
Also note that you did something you shouldn't do in a overwritten version of the updateItem method: Not always call super.updateItem. This can lead to the filled/empty pseudoclasses not being assigned correctly and the item property of the TreeCell not containing the item from the latest updateItem call. You should do something like this instead:
#Override
protected void updateItem(Viewable item, boolean empty) {
textProperty().unbind();
styleProperty().unbind();
if (empty || item == null) {
setText(null);
setStyle(null);
} else {
styleProperty().bind(item.styleProperty());
textProperty().bind(item.titleProperty());
}
super.updateItem(item, empty);
}
I have a list view with the following cell factory:
availableSymbolsTable.setCellFactory(lv -> {
ListCell<Symbol> cell = new ListCell<Symbol>() {
#Override
protected void updateItem(Symbol t, boolean empty) {
super.updateItem(t, empty);
if (empty) {
setText(null);
} else {
setText(t.getSymbolName());
}
}
};
cell.setOnKeyPressed(e ->
{
//This never fires
}
);
cell.setOnMouseEntered(e -> {
//This works
});
cell.setOnMouseClicked(e -> {
if (cell.getItem() != null) {
if(e.getClickCount() == 2)
{
//This works
}
}
});
return cell ;
} );
I have added 3 event handles in the same manner. OnMouseEntered and OnMouseClicked both work as expected. However, OnKeyPressed is never executed. The same goes for OnKeyReleased. When pressing arrow keys, the listview changes the selected row as expected, but my event handler code is never executed. What seems to be the problem?
I am having a problem that I cannot figure out. I am taking a TreeView called treeModel and setting cells using setCellFactory as can be seen by the code. Now within the updateItem, I am setting a CheckBox as a graphic and am associating it with the CheckBoxTreeItem custom class called CheckBoxTreeItemModel. Now every time updateItem runs a new CheckBox is created and a new ChangeListener is created for it.
Now at first everything looks normal. Then I expand the direct children of the root, and begin checking item, but the listener seems to be called multiple time. For every level of TreeItems that is expanded, that is how many times the listener is called on one of the descendants of root. If I click on a child a few leaves down a parent, those listeners are then called multiple times as well. Its weird behavior that might be hard to explain, but the point is I don't think the listener is suppose to be called that many times. Its as if its cached. The problem code is below. Any help understanding why this may be happening would be greatly appreciated.
treeModel.setCellFactory(new Callback<TreeView<String>, TreeCell<String>>() {
#Override
public TreeCell<String> call(TreeView<String> param) {
return new TreeCell<String>() {
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
final TreeCell<String> currCell = this;
this.setOnMouseClicked(new EventHandler<MouseEvent>() {
/*mouse event stuff completely unrelated to problem*/
});
if (empty) {
setText(null);
setGraphic(null);
}
else {
TreeItem<String> treeItem = getTreeItem();
if (treeItem instanceof CheckBoxTreeItemModel) {
System.out.println("Being called.");
final CheckBoxTreeItemModel chkTreeItem = (CheckBoxTreeItemModel) treeItem;
setText(item.toString());
CheckBox chk = new CheckBox();
chk.setSelected(chkTreeItem.getDeleteTick());
if(chkTreeItem.getListener() == null) {
ChangeListener<Boolean> listener = new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable,
Boolean oldValue, Boolean newValue) {
if(newValue) {
//was checked
System.out.println(chkTreeItem.toString()+" was checked!");
chkTreeItem.setDeleteTick(newValue);
}
else {
System.out.println(chkTreeItem.toString()+" was un-checked!");
chkTreeItem.setDeleteTick(newValue);
}
}//end of changed method
};
chkTreeItem.setListener(listener);
}
chk.selectedProperty().removeListener(chkTreeItem.getListener());
chk.selectedProperty().addListener(chkTreeItem.getListener());
chk.indeterminateProperty().bindBidirectional(chkTreeItem.indeterminateProperty());
chk.selectedProperty().bindBidirectional(chkTreeItem.selectedProperty());
setGraphic(chk);
}
else {
setText(item.toString());
setGraphic(null);
}
}
}//end of updateItem
};
}//end of the call method
});
Suggested Approach
I advise scrapping most of your code and using inbuilt CheckBoxTreeCell and CheckBoxTreeItem classes instead. I'm not sure if the inbuilt cells match your requirements, but even if they don't, you could examine the source code for them and compare it with yours and it (should) start to give you a good idea on where you are going wrong.
Potential Issues in Your Code
Reproducing your issue would require more code than you currently supply. But some things to look for are:
Removing and adding the same listener is pointless:
// first line is redundant.
// all listener code is probably unnecessary as you already bindBidirectional.
chk.selectedProperty().removeListener(chkTreeItem.getListener());
chk.selectedProperty().addListener(chkTreeItem.getListener());
updateItem might be called many times for a given cell. don't create new nodes for the cell everytime, instead re-use existing nodes created for the cell.
// replace with a lazily instantiated CheckBox member reference in TreeCell instance.
CheckBox chk = new CheckBox();
You bindBiDirectional but never unbind those bound values.
// should also unbind this values.
chk.indeterminateProperty().bindBidirectional(chkTreeItem.indeterminateProperty());
chk.selectedProperty().bindBidirectional(chkTreeItem.selectedProperty());
Sample Code
Sample updateItem code from the inbuilt CheckBoxTreeCell code:
public class CheckBoxTreeCell<T> extends DefaultTreeCell<T> {
. . .
private final CheckBox checkBox;
private ObservableValue<Boolean> booleanProperty;
private BooleanProperty indeterminateProperty;
. . .
#Override public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
StringConverter c = getConverter();
TreeItem<T> treeItem = getTreeItem();
// update the node content
setText(c != null ? c.toString(treeItem) : (treeItem == null ? "" : treeItem.toString()));
checkBox.setGraphic(treeItem == null ? null : treeItem.getGraphic());
setGraphic(checkBox);
// uninstall bindings
if (booleanProperty != null) {
checkBox.selectedProperty().unbindBidirectional((BooleanProperty)booleanProperty);
}
if (indeterminateProperty != null) {
checkBox.indeterminateProperty().unbindBidirectional(indeterminateProperty);
}
// install new bindings.
// We special case things when the TreeItem is a CheckBoxTreeItem
if (treeItem instanceof CheckBoxTreeItem) {
CheckBoxTreeItem<T> cbti = (CheckBoxTreeItem<T>) treeItem;
booleanProperty = cbti.selectedProperty();
checkBox.selectedProperty().bindBidirectional((BooleanProperty)booleanProperty);
indeterminateProperty = cbti.indeterminateProperty();
checkBox.indeterminateProperty().bindBidirectional(indeterminateProperty);
} else {
Callback<TreeItem<T>, ObservableValue<Boolean>> callback = getSelectedStateCallback();
if (callback == null) {
throw new NullPointerException(
"The CheckBoxTreeCell selectedStateCallbackProperty can not be null");
}
booleanProperty = callback.call(treeItem);
if (booleanProperty != null) {
checkBox.selectedProperty().bindBidirectional((BooleanProperty)booleanProperty);
}
}
}
}
. . .
}
I need drag and drop in my new project. I referred this blogpost. But I'm facing a problem while performing Drop. I cannot get the image which I hold and can't drop into view. DragListner which I used is given below. I don't know how to handle the dropevent.
class MyDragListener implements OnDragListener {
#Override
public boolean onDrag(View view, DragEvent dragEvent) {
int dragAction = dragEvent.getAction();
View dragView = (View) dragEvent.getLocalState();
if (dragAction == DragEvent.ACTION_DRAG_EXITED) {
System.out.println("exit------------");
containsDragable = false;
} else if (dragAction == DragEvent.ACTION_DRAG_ENTERED) {
System.out.println("enter------------");
containsDragable = true;
} else if (dragAction == DragEvent.ACTION_DRAG_ENDED) {
System.out.println("end------------");
dragView.setVisibility(View.VISIBLE);
} else if (dragAction == DragEvent.ACTION_DROP && containsDragable) {
dragView.setVisibility(View.VISIBLE);
}
return true;
}
maybe at first you can print out the
DragEvent.ACTION_DROP
code, and compare it to the value of the dragAction .
if the value is the same then the problem are at containsDragable function.
hope this helps