2

I've got a tableview of floats which work fine. I've made it so the cells are editable, formatted for currency etc. All the cells are right-justified as one would expect a numerical field to be.

One of the columns references a string (instead of a float), which is also editable-- that works too, using the TextFieldTableCell.forTableColumn() method. However I can't figure out how to left-justify the string -- it is right justified like the other columns. I tried using the .setAlignment(Pos.CENTER_LEFT) method, but it only left-justifies when the cell is being edited. After editing, it is right-justified again...

Here's the snippet for that particular column:

 cargoTableTypeCol.setCellFactory((TableColumn<CargoItem, String> p) -> {
     TableCell<CargoItem, String> cell = new TableCell<>();
     cell.setAlignment(Pos.CENTER_LEFT);
     return cell;
 });
 cargoTableTypeCol.setCellFactory(TextFieldTableCell.forTableColumn());
 cargoTableTypeCol.setCellValueFactory(cellData -> cellData.getValue().typeProperty());

And here's what it looks like: enter image description here

as you can see the cell with "coal" in it is not left-justified. Iknow it's trivial, but frustrating nonetheless.

Tel
  • 111
  • 2
  • 10
  • 1
    You set the cell factory twice, so the first factory you pass will have no effect. – James_D Sep 06 '15 at 19:41
  • Ah, thanks for the heads up James. So how would I integrate the`TextFieldTableCell.forTableColumn()` (for editing) with the `setAlignment()` method (for formatting the edited value)? – Tel Sep 06 '15 at 23:26
  • Added an answer. In this particular use case, I would recommend using CSS, as in @UgurcanYildirim's answer. – James_D Sep 07 '15 at 00:10

2 Answers2

3

I suggest you to try the following: cargoTableTypeCol.setStyle("-fx-alignment: CENTER-LEFT;");

Ugurcan Yildirim
  • 5,973
  • 3
  • 42
  • 73
1

Using CSS, as in @UgurcanYildirim's answer (or using an external style sheet), is the best solution for this particular use case.

The reason the code in the question does not work is that the cellFactory is a property and follows the usual rules for properties. In particular, if you call setCellFactory(...) with one value and subsequently call it with a different value, the second value replaces the first, and the first is discarded. In other words, a TableColumn has one and only one cellFactory.

For a use case where you genuinely need to modify the cell returned by one cell factory, you can use the following (essentially just a decorator pattern):

Callback<TableColumn<CargoItem, String>, TableCell<CargoItem, String>> defaultCellFactory
    = TextFieldTableCell.forTableColumn();

cargoTableTypeCol.setCellFactory(col -> {
    TableCell<CargoItem, String> cell = defaultCellFactory.call(col);
    cell.setAlignment(Pos.CENTER_LEFT);
    return cell ;
});
Ugurcan Yildirim
  • 5,973
  • 3
  • 42
  • 73
James_D
  • 201,275
  • 16
  • 291
  • 322