Using this example here:
https://stackoverflow.com/a/30509195
Works great to create multiple tables for summation rows. I also needed the scrollbar visible on the bottom table as well. However, the bottom table's scrollbar doesn't sync with the main table (at first with empty content). When there is data, the scrollbar syncs properly.
When you add data to the table, then remove the data, again, scroll bars sync properly. So I know they can still be synced with a table with empty content.
Here is the example code (with two buttons on the top to add and clear items)
package testsummary;
import java.text.Format;
import java.time.LocalDate;
import java.time.Month;
import java.util.Set;
import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import javafx.util.Callback;
/**
* Table with a summary table. The summary table is a 2nd table which is
* synchronized with the primary table.
*
* TODO: + always show vertical bars for both the primary and the summary table,
* otherweise the width of both tables wouldn't be the same + hide the
* horizontal scrollbar of the summary table
*
*/
public class SummaryTableDemo extends Application
{
private TableView<Data> mainTable = new TableView<>();
private TableView<SumData> sumTable = new TableView<>();
private final ObservableList<Data> data
= FXCollections.observableArrayList();
// TODO: calculate values
private final ObservableList<SumData> sumData
= FXCollections.observableArrayList(
new SumData("Sum", 0.0, 0.0, 0.0),
new SumData("Min", 0.0, 0.0, 0.0),
new SumData("Max", 0.0, 0.0, 0.0)
);
final HBox hb = new HBox();
public static void main(String[] args)
{
launch(args);
}
#Override
public void start(Stage stage)
{
Scene scene = new Scene(new Group());
// load css
// scene.getStylesheets().addAll(getClass().getResource("application.css").toExternalForm());
stage.setTitle("Table View Sample");
stage.setWidth(250);
stage.setHeight(550);
// setup table columns
setupMainTableColumns();
setupSumTableColumns();
// fill tables with data
mainTable.setItems(data);
sumTable.setItems(sumData);
// set dimensions
sumTable.setPrefHeight(90);
// bind/sync tables
for (int i = 0; i < mainTable.getColumns().size(); i++)
{
TableColumn<Data, ?> mainColumn = mainTable.getColumns().get(i);
TableColumn<SumData, ?> sumColumn = sumTable.getColumns().get(i);
// sync column widths
sumColumn.prefWidthProperty().bind(mainColumn.widthProperty());
// sync visibility
sumColumn.visibleProperty().bindBidirectional(mainColumn.visibleProperty());
}
// allow changing of column visibility
//mainTable.setTableMenuButtonVisible(true);
// hide header (variation of jewelsea's solution: http://stackoverflow.com/questions/12324464/how-to-javafx-hide-background-header-of-a-tableview)
sumTable.getStyleClass().add("tableview-header-hidden");
// hide horizontal scrollbar via styles
// sumTable.getStyleClass().add("sumtable");
// create container
BorderPane bp = new BorderPane();
Button addButton = new Button("+");
Button clearButton = new Button("X");
addButton.setOnAction((ActionEvent c) ->
{
data.add(new Data(LocalDate.of(2015, Month.JANUARY, 11), 40.0, 50.0, 60.0));
});
clearButton.setOnAction((ActionEvent c) ->
{
data.clear();
});
HBox buttonBar = new HBox(clearButton, addButton);
bp.setTop(buttonBar);
bp.setCenter(mainTable);
bp.setBottom(sumTable);
// fit content
bp.prefWidthProperty().bind(scene.widthProperty());
bp.prefHeightProperty().bind(scene.heightProperty());
((Group) scene.getRoot()).getChildren().addAll(bp);
stage.setScene(scene);
stage.show();
// synchronize scrollbars (must happen after table was made visible)
ScrollBar mainTableHorizontalScrollBar = findScrollBar(mainTable, Orientation.HORIZONTAL);
ScrollBar sumTableHorizontalScrollBar = findScrollBar(sumTable, Orientation.HORIZONTAL);
mainTableHorizontalScrollBar.valueProperty().bindBidirectional(sumTableHorizontalScrollBar.valueProperty());
}
/**
* Primary table column mapping.
*/
private void setupMainTableColumns()
{
TableColumn<Data, LocalDate> dateCol = new TableColumn<>("Date");
dateCol.setPrefWidth(120);
dateCol.setCellValueFactory(new PropertyValueFactory<>("date"));
TableColumn<Data, Double> value1Col = new TableColumn<>("Value 1");
value1Col.setPrefWidth(90);
value1Col.setCellValueFactory(new PropertyValueFactory<>("value1"));
value1Col.setCellFactory(new FormattedTableCellFactory<>(TextAlignment.RIGHT));
TableColumn<Data, Double> value2Col = new TableColumn<>("Value 2");
value2Col.setPrefWidth(90);
value2Col.setCellValueFactory(new PropertyValueFactory<>("value2"));
value2Col.setCellFactory(new FormattedTableCellFactory<>(TextAlignment.RIGHT));
TableColumn<Data, Double> value3Col = new TableColumn<>("Value 3");
value3Col.setPrefWidth(90);
value3Col.setCellValueFactory(new PropertyValueFactory<>("value3"));
value3Col.setCellFactory(new FormattedTableCellFactory<>(TextAlignment.RIGHT));
mainTable.getColumns().addAll(dateCol, value1Col, value2Col, value3Col);
}
/**
* Summary table column mapping.
*/
private void setupSumTableColumns()
{
TableColumn<SumData, String> textCol = new TableColumn<>("Text");
textCol.setCellValueFactory(new PropertyValueFactory<>("text"));
TableColumn<SumData, Double> value1Col = new TableColumn<>("Value 1");
value1Col.setCellValueFactory(new PropertyValueFactory<>("value1"));
value1Col.setCellFactory(new FormattedTableCellFactory<>(TextAlignment.RIGHT));
TableColumn<SumData, Double> value2Col = new TableColumn<>("Value 2");
value2Col.setCellValueFactory(new PropertyValueFactory<>("value2"));
value2Col.setCellFactory(new FormattedTableCellFactory<>(TextAlignment.RIGHT));
TableColumn<SumData, Double> value3Col = new TableColumn<>("Value 3");
value3Col.setCellValueFactory(new PropertyValueFactory<>("value3"));
value3Col.setCellFactory(new FormattedTableCellFactory<>(TextAlignment.RIGHT));
sumTable.getColumns().addAll(textCol, value1Col, value2Col, value3Col);
}
/**
* Find the horizontal scrollbar of the given table.
*
* #param table
* #return
*/
private ScrollBar findScrollBar(TableView<?> table, Orientation orientation)
{
// this would be the preferred solution, but it doesn't work. it always gives back the vertical scrollbar
// return (ScrollBar) table.lookup(".scroll-bar:horizontal");
//
// => we have to search all scrollbars and return the one with the proper orientation
Set<Node> set = table.lookupAll(".scroll-bar");
for (Node node : set)
{
ScrollBar bar = (ScrollBar) node;
if (bar.getOrientation() == orientation)
{
return bar;
}
}
return null;
}
/**
* Data for primary table rows.
*/
public static class Data
{
private final ObjectProperty<LocalDate> date;
private final SimpleDoubleProperty value1;
private final SimpleDoubleProperty value2;
private final SimpleDoubleProperty value3;
public Data(LocalDate date, double value1, double value2, double value3)
{
this.date = new SimpleObjectProperty<LocalDate>(date);
this.value1 = new SimpleDoubleProperty(value1);
this.value2 = new SimpleDoubleProperty(value2);
this.value3 = new SimpleDoubleProperty(value3);
}
public final ObjectProperty<LocalDate> dateProperty()
{
return this.date;
}
public final LocalDate getDate()
{
return this.dateProperty().get();
}
public final void setDate(final LocalDate date)
{
this.dateProperty().set(date);
}
public final SimpleDoubleProperty value1Property()
{
return this.value1;
}
public final double getValue1()
{
return this.value1Property().get();
}
public final void setValue1(final double value1)
{
this.value1Property().set(value1);
}
public final SimpleDoubleProperty value2Property()
{
return this.value2;
}
public final double getValue2()
{
return this.value2Property().get();
}
public final void setValue2(final double value2)
{
this.value2Property().set(value2);
}
public final SimpleDoubleProperty value3Property()
{
return this.value3;
}
public final double getValue3()
{
return this.value3Property().get();
}
public final void setValue3(final double value3)
{
this.value3Property().set(value3);
}
}
/**
* Data for summary table rows.
*/
public static class SumData
{
private final SimpleStringProperty text;
private final SimpleDoubleProperty value1;
private final SimpleDoubleProperty value2;
private final SimpleDoubleProperty value3;
public SumData(String text, double value1, double value2, double value3)
{
this.text = new SimpleStringProperty(text);
this.value1 = new SimpleDoubleProperty(value1);
this.value2 = new SimpleDoubleProperty(value2);
this.value3 = new SimpleDoubleProperty(value3);
}
public final SimpleStringProperty textProperty()
{
return this.text;
}
public final java.lang.String getText()
{
return this.textProperty().get();
}
public final void setText(final java.lang.String text)
{
this.textProperty().set(text);
}
public final SimpleDoubleProperty value1Property()
{
return this.value1;
}
public final double getValue1()
{
return this.value1Property().get();
}
public final void setValue1(final double value1)
{
this.value1Property().set(value1);
}
public final SimpleDoubleProperty value2Property()
{
return this.value2;
}
public final double getValue2()
{
return this.value2Property().get();
}
public final void setValue2(final double value2)
{
this.value2Property().set(value2);
}
public final SimpleDoubleProperty value3Property()
{
return this.value3;
}
public final double getValue3()
{
return this.value3Property().get();
}
public final void setValue3(final double value3)
{
this.value3Property().set(value3);
}
}
/**
* Formatter for table cells: allows you to align table cell values
* left/right/center
*
* Example for alignment form
* http://docs.oracle.com/javafx/2/fxml_get_started/fxml_tutorial_intermediate.htm
*
* #param <S>
* #param <T>
*/
public static class FormattedTableCellFactory<S, T> implements Callback<TableColumn<S, T>, TableCell<S, T>>
{
private TextAlignment alignment = TextAlignment.LEFT;
private Format format;
public FormattedTableCellFactory()
{
}
public FormattedTableCellFactory(TextAlignment alignment)
{
this.alignment = alignment;
}
public TextAlignment getAlignment()
{
return alignment;
}
public void setAlignment(TextAlignment alignment)
{
this.alignment = alignment;
}
public Format getFormat()
{
return format;
}
public void setFormat(Format format)
{
this.format = format;
}
#Override
#SuppressWarnings("unchecked")
public TableCell<S, T> call(TableColumn<S, T> p)
{
TableCell<S, T> cell = new TableCell<S, T>()
{
#Override
public void updateItem(Object item, boolean empty)
{
if (item == getItem())
{
return;
}
super.updateItem((T) item, empty);
if (item == null)
{
super.setText(null);
super.setGraphic(null);
} else if (format != null)
{
super.setText(format.format(item));
} else if (item instanceof Node)
{
super.setText(null);
super.setGraphic((Node) item);
} else
{
super.setText(item.toString());
super.setGraphic(null);
}
}
};
cell.setTextAlignment(alignment);
switch (alignment)
{
case CENTER:
cell.setAlignment(Pos.CENTER);
break;
case RIGHT:
cell.setAlignment(Pos.CENTER_RIGHT);
break;
default:
cell.setAlignment(Pos.CENTER_LEFT);
break;
}
return cell;
}
}
}
No solution (which probably would require some real work in the bowels of VirtualFlow and/or TableViewSkin) but a dirty trick: add/remove data after wiring the scrollBars
addButton.fire();
Platform.runLater(( ) -> {
clearButton.fire();
});
The drawback is a short but perceptible flicker ...
Update
After a bit of digging ("geht-nicht-gibt's-nicht" - don't know the English idiom, sry) I found a way to force the VirtualFlow into an initial layout pass even if there are no items: the basic idea is to temporarily set the flow's cellCount > 0 even if there are no items. The tricky part is to do it at the right time in the skin's life: only once, sometime early but only after the normal layout has happened.
The implementation below
has a flag to indicate whether or not to fake the itemCount
sets the flag in a listener to the containing window's showing property: this assumes a normal setting of the default skin while being added to the scenegraph
overridden getItemCount to return at least 1 if the flag is set
overridden layoutChildren that forces a fake layout if the flag is set
the forced layout is achieved by calling updateItemCount twice: once with and once without flag
Still dirty, but more fun :)
public static class TweakedTableSkin<T> extends TableViewSkin<T> {
private boolean forceNotEmpty = false;
ChangeListener showingListener = (src, ov, nv) -> {
initForceNotEmpty(src);
};
public TweakedTableSkin(TableView<T> control) {
super(control);
Window window = getSkinnable().getScene().getWindow();
if (window != null)
window.showingProperty().addListener(showingListener);
}
/**
* Overridden to force a re-layout with faked itemCount after calling
* super if the fake flag is true.
*/
#Override
protected void layoutChildren(double x, double y, double w, double h) {
super.layoutChildren(x, y, w, h);
if (forceNotEmpty) {
forceNotEmptyLayout();
}
}
/**
* Callback from listener installed on window's showing property.
* Implemented to set the forceNotEmpty flag and remove the listener.
*/
private void initForceNotEmpty(ObservableValue src) {
forceNotEmpty = true;
src.removeListener(showingListener);
}
/**
* Enforces a layout pass on the flow with at least one row.
* Resets the forceNotEmpty flag and triggers a second
* layout pass with the correct count.
*/
private void forceNotEmptyLayout() {
if (!forceNotEmpty) return;
updateItemCount();
forceNotEmpty = false;
updateItemCount();
}
/**
* Overridden to return at least 1 if forceNotEmpty is true.
*/
#Override
protected int getItemCount() {
int itemCount = super.getItemCount();
if (forceNotEmpty && itemCount == 0) {
itemCount = 1;
}
return itemCount;
}
}
Usage by extending TableView with an overridden createDefaultSkin:
private TableView<Data> mainTable = new TableView<>() {
#Override
protected Skin<?> createDefaultSkin() {
return new TweakedTableSkin<>(this);
}
};
Related
Is there a way to create "accounting" style cells in JavaFX tables?
By accounting I mean having the dollar sign left-aligned and the values right-aligned in the cell. Here is what that looks like in Excel:
Here is what I tried so far:
public class PriceTableCell<S> extends TableCell<S, Long>
{
public PriceTableCell()
{
final Label label = new Label("$");
this.setAlignment(Pos.CENTER_RIGHT);
this.setContentDisplay(ContentDisplay.LEFT);
this.setGraphic(label);
}
#Override
protected void updateItem(Long item, boolean empty)
{
if (item == null || empty)
{
this.setText(null);
return;
}
this.setText(String.format(Locale.ENGLISH, "%,d.%02d", item / 100, Math.abs(item % 100)));
}
}
Unfortunately I did not find a way to set separate alignments for graphic and text. JavaFX renders the above as follows:
Using two labels in an AnchorPane should work.
(Update: Following #kleopatra's suggestion, I incorporated a DecimalFormat into this solution, which will (at least partially) localize the currency symbol, as well as the number of decimal digits, etc. This will make the assumption that the currency symbol is displayed to the left of the currency value, which isn't necessarily true for all currencies, but the assumption is somewhat implicit in the question anyway.)
public class PriceTableCell<S> extends TableCell<S, Long> {
private final AnchorPane pane ;
private final Label valueLabel ;
// locale-aware currency format to use for formatting
private DecimalFormat format;
public PriceTableCell() {
// grab an instance
format = (DecimalFormat) NumberFormat.getCurrencyInstance();
//get the currency symbol
String symbol = format.getCurrency().getSymbol();
// replace the currency symbol with an empty string
DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
symbols.setCurrencySymbol("");
format.setDecimalFormatSymbols(symbols);
Label currencySignLabel = new Label(symbol);
valueLabel = new Label();
pane = new AnchorPane(currencySignLabel, valueLabel);
AnchorPane.setLeftAnchor(currencySignLabel, 0.0);
AnchorPane.setRightAnchor(valueLabel, 0.0);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
#Override
protected void updateItem(Long price, boolean empty) {
super.updateItem(price, empty);
if (empty) {
setGraphic(null);
} else {
// manual formatting
//String text = String.format("%,d.%02d", price / 100, Math.abs(price % 100));
valueLabel.setText(format.format(price));
setGraphic(pane);
}
}
}
Here is a SSCCE:
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Random;
import java.util.function.Function;
import javafx.application.Application;
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class TableViewWithAccountingStyleCell extends Application {
public static class PriceTableCell<S> extends TableCell<S, Long> {
private final AnchorPane pane ;
private final Label valueLabel ;
// locale-aware currency format to use for formatting
private DecimalFormat format;
public PriceTableCell() {
// grab an instance
format = (DecimalFormat) NumberFormat.getCurrencyInstance();
//get the currency symbol
String symbol = format.getCurrency().getSymbol();
// replace the currency symbol with an empty string
DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
symbols.setCurrencySymbol("");
format.setDecimalFormatSymbols(symbols);
Label currencySignLabel = new Label(symbol);
valueLabel = new Label();
pane = new AnchorPane(currencySignLabel, valueLabel);
AnchorPane.setLeftAnchor(currencySignLabel, 0.0);
AnchorPane.setRightAnchor(valueLabel, 0.0);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
#Override
protected void updateItem(Long price, boolean empty) {
super.updateItem(price, empty);
if (empty) {
setGraphic(null);
} else {
// manual formatting
//String text = String.format("%,d.%02d", price / 100, Math.abs(price % 100));
valueLabel.setText(format.format(price));
setGraphic(pane);
}
}
}
public static class Item {
private final StringProperty name = new SimpleStringProperty();
private final LongProperty price = new SimpleLongProperty();
public Item(String name, long price) {
setName(name);
setPrice(price);
}
public StringProperty nameProperty() {
return name ;
}
public final String getName() {
return nameProperty().get();
}
public final void setName(String name) {
nameProperty().set(name);
}
public LongProperty priceProperty() {
return price ;
}
public final long getPrice() {
return priceProperty().get();
}
public final void setPrice(long price) {
priceProperty().set(price);
}
}
#Override
public void start(Stage primaryStage) {
TableView<Item> table = new TableView<>();
table.getColumns().add(column("Item", Item::nameProperty));
TableColumn<Item, Long> priceColumn = column("Price", item -> item.priceProperty().asObject());
priceColumn.setPrefWidth(300);
priceColumn.setCellFactory(tc -> new PriceTableCell<>());
table.getColumns().add(priceColumn);
Random rng = new Random();
for (int i = 1 ; i <= 20 ; i++) {
table.getItems().add(new Item("Item "+i, rng.nextInt(1_000_000)));
}
Scene scene = new Scene(table);
primaryStage.setScene(scene);
primaryStage.show();
}
private <S,T> TableColumn<S,T> column(String name, Function<S, ObservableValue<T>> property) {
TableColumn<S,T> column = new TableColumn<>(name);
column.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
return column ;
}
public static void main(String[] args) {
launch(args);
}
}
which produces
I'm stuck with trying to format Long values in a TableView with JavaFX.
I have following class to store the rows that I want to display on the table:
import java.text.DecimalFormat;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleStringProperty;
public class DataByCurrencyPairRow {
private DecimalFormat integerFormat = new DecimalFormat("#,###");
private SimpleStringProperty currencyPair = new SimpleStringProperty("");
private SimpleDoubleProperty shareOfTotalVolume = new SimpleDoubleProperty(0);
private SimpleLongProperty totalVolume = new SimpleLongProperty(0);
private SimpleLongProperty currencyBought = new SimpleLongProperty(0);
private SimpleLongProperty currencySold = new SimpleLongProperty(0);
private SimpleLongProperty monthlyAverage = new SimpleLongProperty(0);
public DataByCurrencyPairRow() {
currencyPair.set("");
shareOfTotalVolume.set(0);
totalVolume.set(0);
currencyBought.set(0);
currencySold.set(0);
monthlyAverage.set(0);
}
public String getCurrencyPair() {
return currencyPair.getValue();
}
public void setCurrencyPair(String currencyPair) {
this.currencyPair.setValue(currencyPair);
}
public Long getMonthlyAverage() {
return monthlyAverage.getValue();
}
public void setMonthlyAverage(Long monthlyAverage) {
this.monthlyAverage.setValue(monthlyAverage);
}
public Long getCurrencySold() {
return currencySold.getValue();
}
public void setCurrencySold(Long currencySold) {
this.currencySold.setValue(currencySold);
}
public Long getCurrencyBought() {
return currencyBought.getValue();
}
public void setCurrencyBought(Long currencyBought) {
this.currencyBought.setValue(currencyBought);
}
public Long getTotalVolume() {
return totalVolume.getValue();
}
public void setTotalVolume(Long totalVolume) {
this.totalVolume.setValue(totalVolume);
}
public Double getShareOfTotalVolume() {
return shareOfTotalVolume.getValue();
}
public void setShareOfTotalVolume(Double shareOfTotalVolume) {
this.shareOfTotalVolume.setValue(shareOfTotalVolume);
}
}
Then I have the controller with initialize method where I have been trying to override the updateItem method to get the table to show comma as a thousand separator:
public class MainController {
private static final String DEFAULT_TIME_HORIZON = new String("0");
private final NumberFormat integerFormat = new DecimalFormat("#,###");
#FXML
TableView<DataByCurrencyPairRow> tableTransactionsByCurrencyPair;
#FXML
TableColumn<DataByCurrencyPairRow, Long> columnTotal;
#FXML
void initialize() {
columnTotal.setCellFactory(
new Callback<TableColumn<DataByCurrencyPairRow, SimpleLongProperty>, TableCell<DataByCurrencyPairRow, SimpleLongProperty>>() {
#Override
public TableCell<DataByCurrencyPairRow, SimpleLongProperty> call(TableColumn<DataByCurrencyPairRow, SimpleLongProperty> param
) {
return new TableCell<DataByCurrencyPairRow, SimpleLongProperty>() {
#Override
protected void updateItem(SimpleLongProperty item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText("0");
setStyle("");
} else {
setText(integerFormat.format(item.longValue()));
}
}
};
}
}
);
And this is the method that populates the TableView:
public void updateByCurrencyPairTable() {
System.out.println("#MainController: Updating data in table view Markets volumes by currency pair");
ObservableList<DataByCurrencyPairRow> data = tableTransactionsByCurrencyPair.getItems();
data.clear();
// Add row items to the table view Markets volume by currency
for (DataByCurrencyPairRow row : customer.getDataByCurrencyPairR12m().getDataByCurrencyPair()) {
data.add(row);
}
}
Please help me by showing how to do this!! I also tried to override the updateItem method as Long instead of SimpleLongProperty and my IDE accepted the code but still the number is not formatted in the table.
Thank you guys in advance!!!
LongProperty implements ObservableValue<Number>, not ObservableValue<Long> (or ObservableValue<SimpleLongProperty>). So your table columns need to be of type TableColumn<DataByCurrencyPair, Number> and your cell factory needs to match those types accordingly.
Here's a simple example of a formatted column with Longs:
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Random;
import javafx.application.Application;
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
public class TableWithFormattedLong extends Application {
private final NumberFormat integerFormat = new DecimalFormat("#,###");
#Override
public void start(Stage primaryStage) {
TableView<Item> table = new TableView<>();
TableColumn<Item, String> itemColumn = new TableColumn<>("Item");
itemColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
TableColumn<Item, Number> valueColumn = new TableColumn<>("Value");
valueColumn.setCellValueFactory(cellData -> cellData.getValue().valueProperty());
valueColumn.setCellFactory(tc -> new TableCell<Item, Number>() {
#Override
protected void updateItem(Number value, boolean empty) {
super.updateItem(value, empty);
if (value == null || empty) {
setText("");
} else {
setText(integerFormat.format(value));
}
}
});
table.getColumns().add(itemColumn);
table.getColumns().add(valueColumn);
Random rng = new Random();
for (int i = 1 ; i <= 20 ; i++) {
table.getItems().add(new Item("Item "+i, rng.nextLong()));
}
primaryStage.setScene(new Scene(table, 600, 600));
primaryStage.show();
}
public static class Item {
private final StringProperty name = new SimpleStringProperty();
private final LongProperty value = new SimpleLongProperty();
public Item(String name, long value) {
setName(name);
setValue(value);
}
public final StringProperty nameProperty() {
return this.name;
}
public final String getName() {
return this.nameProperty().get();
}
public final void setName(final String name) {
this.nameProperty().set(name);
}
public final LongProperty valueProperty() {
return this.value;
}
public final long getValue() {
return this.valueProperty().get();
}
public final void setValue(final long value) {
this.valueProperty().set(value);
}
}
public static void main(String[] args) {
launch(args);
}
}
There is no need to set the Cellfactory, just set the CellValueFactory.
TableColumn<DataByCurrencyPairRow, String> columnTotal;
columnTotal.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<DataByCurrencyPairRow,String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(CellDataFeatures<DataByCurrencyPairRow, String> param) {
DataByCurrencyPairRow value = param.getValue();
return new ReadOnlyStringWrapper(NumberFormat.getNumberInstance(Locale.US).format(123123)); //replace the number with the calculated total
}
});
I have a Javafx TableView where I can add new Rows by double Click on an empty Row at the End of my "filled" / Textfield filled Rows.
My Problem is,if i add some Rows ,Java don't give me more of the empty Rows I could double click to add some Rows.
Edit:removed some unnessary log
To see what i mean, here is the Code:
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TextArea;
import javafx.util.Callback;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
interface inside_table
{
public void Select_Row_by_Col(int index);
}
public class Supermain extends Application {
ObservableList<myTextRow> data;
#Override
public void start(Stage primaryStage) {
ArrayList myindizes=new ArrayList();
final TableView<myTextRow> table = new TableView<>();
table.setEditable(true);
table.setStyle("-fx-text-wrap: true;");
//Table columns
TableColumn<myTextRow, String> clmID = new TableColumn<>("ID");
clmID.setMinWidth(160);
clmID.setCellValueFactory(new PropertyValueFactory<>("ID"));
TableColumn<myTextRow, String> clmtext = new TableColumn<>("Text");
clmtext.setMinWidth(160);
clmtext.setCellValueFactory(new PropertyValueFactory<>("text"));
clmtext.setCellFactory(new TextFieldCellFactory("text"));
TableColumn<myTextRow, String> clmtext2 = new TableColumn<>("Text2");
clmtext2.setMinWidth(160);
clmtext2.setCellValueFactory(new PropertyValueFactory<>("text2"));
clmtext2.setCellFactory(new TextFieldCellFactory("text2"));
//Add data
data = FXCollections.observableArrayList(
new myTextRow(5, "Lorem","bla"),
new myTextRow(2, "Ipsum","bla")
);
table.getColumns().addAll(clmID, clmtext,clmtext2);
table.setItems(data);
table.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
if (mouseEvent.getClickCount() == 2 && mouseEvent.getY()>24) {
data.add(new myTextRow(td_get_biggest_ID() + 1,"",""));
table.selectionModelProperty().get().select(data.size()-1);
}
}
}
});
HBox hBox = new HBox();
hBox.setSpacing(5.0);
hBox.setPadding(new Insets(5, 5, 5, 5));
Button btn = new Button();
btn.setText("Get Data");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
for (myTextRow data1 : data) {
System.out.println("data:" + data1.getText2());
}
}
});
hBox.getChildren().add(btn);
BorderPane pane = new BorderPane();
pane.setTop(hBox);
pane.setCenter(table);
primaryStage.setScene(new Scene(pane, 640, 480));
primaryStage.show();
class I_table implements inside_table{
#Override
public void Select_Row_by_Col(int index) {
table.getSelectionModel().select(index);
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
public static class TextFieldCellFactory
implements Callback<TableColumn<myTextRow, String>, TableCell<myTextRow, String>> {
private String ColumnName;
public TextFieldCellFactory(String ColumnName){
this.ColumnName=ColumnName;
}
#Override
public TableCell<myTextRow, String> call(TableColumn<myTextRow, String> param) {
TextFieldCell textFieldCell = new TextFieldCell(this.ColumnName);
return textFieldCell;
}
public static class TextFieldCell extends TableCell<myTextRow, String> {
private TextArea textField;
private StringProperty boundToCurrently = null;
private String last_text;
private String ColumnName;
public TextFieldCell(String cname) {
textField = new TextArea();
textField.setWrapText(true);
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
last_text="";
this.ColumnName=cname;
this.setGraphic(textField);
textField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
if(this.ColumnName=="text2"){
if(isNowFocused){last_text=textField.getText();System.out.println("NOW focus "+last_text);}
if (! isNowFocused && ! isValid(textField.getText())) {
textField.setText(last_text);
//textField.setText("00:00:00:00");
textField.selectAll();
System.out.println("blur");
}
}
});
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
// Show the Text Field
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
// myindizes.add(getIndex());
// Retrieve the actual String Property that should be bound to the TextField
// If the TextField is currently bound to a different StringProperty
// Unbind the old property and rebind to the new one
ObservableValue<String> ov = getTableColumn().getCellObservableValue(getIndex());
SimpleStringProperty sp = (SimpleStringProperty) ov;
if (this.boundToCurrently == null) {
this.boundToCurrently = sp;
this.textField.textProperty().bindBidirectional(sp);
} else if (this.boundToCurrently != sp) {
this.textField.textProperty().unbindBidirectional(this.boundToCurrently);
this.boundToCurrently = sp;
this.textField.textProperty().bindBidirectional(this.boundToCurrently);
}
double height = real_lines_height(textField.getText(), this.getWidth(), 30, 22);
textField.setPrefHeight(height);
textField.setMaxHeight(height);
textField.setMaxHeight(Double.MAX_VALUE);
// if height bigger than the biggest height in the row
//-> change all heights of the row(textfields ()typeof textarea) to this height
// else leave the height as it is
//System.out.println("item=" + item + " ObservableValue<String>=" + ov.getValue());
//this.textField.setText(item); // No longer need this!!!
} else {
this.setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}//update
private boolean isValid(String s){
String splitArray[] = s.split(":");
if (splitArray.length != 4) {
System.out.println("false");
return false;
}
for (int i = 0; i < splitArray.length; i++) {
if (splitArray[i].length() != 2) {
System.out.println("false");
return false;
}
if (!splitArray[i].substring(0, 1).matches("[0-9]")) {
System.out.println("no number1");
return false;
}
if (!splitArray[i].substring(1, 2).matches("[0-9]")) {
System.out.println("no number2");
return false;
}
if (i < 3) {
int itest = Integer.parseInt(splitArray[i]);
if (itest > 59) {
System.out.println(itest + " ist zu groß!");
return false;
}
} else {
int itest2 = Integer.parseInt(splitArray[i]);
if (itest2 > Math.floor(25)) {
System.out.println(itest2 + " ist zu groß!");
return false;
}
//framerate!!!!!
}
System.out.println("splits: " + splitArray[i]);
//if( el.charAt(0).)
}
return true;
}
}
}
public class myTextRow {
private final SimpleIntegerProperty ID;
private final SimpleStringProperty text;
private final SimpleStringProperty text2;
public myTextRow(int ID, String text,String text2) {
this.ID = new SimpleIntegerProperty(ID);
this.text = new SimpleStringProperty(text);
this.text2 = new SimpleStringProperty(text2);
}
//setter
public void setID(int id) {
this.ID.set(id);
}
public void setText(String text) {
this.text.set(text);
}
public void setText2(String text) {
this.text2.set(text);
}
//getter
public int getID() {
return ID.get();
}
public String getText() {
return text.get();
}
public String getText2() {
return text2.get();
}
//properties
public StringProperty textProperty() {
return text;
}
public StringProperty text2Property() {
return text2;
}
public IntegerProperty IDProperty() {
return ID;
}
}
private static double real_lines_height(String s, double width, double heightCorrector, double widthCorrector) {
HBox h = new HBox();
Label l = new Label("Text");
h.getChildren().add(l);
Scene sc = new Scene(h);
l.applyCss();
double line_height = l.prefHeight(-1);
int new_lines = s.replaceAll("[^\r\n|\r|\n]", "").length();
// System.out.println("new lines= "+new_lines);
String[] lines = s.split("\r\n|\r|\n");
// System.out.println("line count func= "+ lines.length);
int count = 0;
//double rest=0;
for (int i = 0; i < lines.length; i++) {
double text_width = get_text_width(lines[i]);
double plus_lines = Math.ceil(text_width / (width - widthCorrector));
if (plus_lines > 1) {
count += plus_lines;
//rest+= (text_width / (width-widthCorrector)) - plus_lines;
} else {
count += 1;
}
}
//count+=(int) Math.ceil(rest);
count += new_lines - lines.length;
return count * line_height + heightCorrector;
}
private static double get_text_width(String s) {
HBox h = new HBox();
Label l = new Label(s);
l.setWrapText(false);
h.getChildren().add(l);
Scene sc = new Scene(h);
l.applyCss();
// System.out.println("FXMLDocumentController.get_text_width(): "+l.prefWidth(-1));
return l.prefWidth(-1);
}
public int td_get_biggest_ID() {
int biggest = 0;
for (int i = 0; i < data.size(); i++) {
if (((myTextRow) data.get(i)).getID() > biggest) {
biggest = ((myTextRow) data.get(i)).getID();
}
}
return biggest;
}
}
Just click anywhere else on the TableView but make sure it's at least 24 pixels from the top; This will work since you've added the event handler is added to the TableView...
If you only want to use the last row, then use a custom rowFactory and handle the events there.
Add a placeholder item to the TableView items that marks the row that is used for adding new elements (for some reason the selection model doesn't like null):
final myTextRow addPlaceHolder = new myTextRow(Integer.MIN_VALUE, null, null);
...
//Add data
data = FXCollections.observableArrayList(
new myTextRow(5, "Lorem", "bla"),
new myTextRow(2, "Ipsum", "bla"),
addPlaceHolder
);
make sure your TextFieldCells treat null values as empty rows:
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty && item != null) {
// Show the Text Field
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
...
make sure the first column does not display anything for the placeholder
//Table columns
TableColumn<myTextRow, Number> clmID = new TableColumn<>("ID");
clmID.setMinWidth(160);
clmID.setCellValueFactory(cdf -> {
myTextRow item = cdf.getValue();
return item == addPlaceHolder ? Bindings.createObjectBinding(() -> null) : item.IDProperty();
});
and use the following rowFactory to handle adding the items (you don't need the updateItem part unless you need to add a style class to the TableRow; you need not extend TableRow in this case)
table.setRowFactory(tv -> new TableRow<myTextRow>() {
{
setOnMouseClicked(mouseEvent -> {
if (mouseEvent.getButton() == MouseButton.PRIMARY
&& mouseEvent.getClickCount() == 2
&& !isEmpty()
&& getItem() == addPlaceHolder) {
data.add(data.size() - 1, new myTextRow(td_get_biggest_ID() + 1, "", ""));
table.selectionModelProperty().get().select(data.size() - 1);
mouseEvent.consume();
}
});
}
#Override
protected void updateItem(myTextRow item, boolean empty) {
super.updateItem(item, empty);
// add style class for row containing addPlaceHolder
List<String> classes = getStyleClass();
final String clazz = "add-row";
if (item == addPlaceHolder) {
if (!classes.contains(clazz)) {
classes.add(clazz);
}
} else {
classes.remove(clazz);
}
}
});
My users can create jobs that are added to a MySQL database. The jobs have a priority (1, 2 or 3). What I would like to do is modify the colour of individual rows based on the priority of the job, for example prioirty 3 is a red row as this is a more urgent job, priority 1 is a green row as it has a lower urgency.
I have a job model class that has a getter/setter for priority;
public int getPrioritySetting() {
return prioritySetting;
}
public void setPrioritySetting(final int prioritySetting) {
this.prioritySetting = prioritySetting;
}
I have two questions, what is the "easiest" way to get the priority of each inidivual job from the MySQL database and (using this), what is the "easiest" way to modify the appearance of the row? I'm currently using TableView in JavaFX with FXML files built through scenebuilder.
I don't understand the first question: presumably you are getting the Job objects from the database at some point anyway, so you would just populate the prioritySetting field when you do so.
To change the appearance of the row, use a row factory, and set some CSS pseudoclasses
PseudoClass highPriority = PseudoClass.getPseudoClass("high-priority");
PseudoClass lowPriority = PseudoClass.getPseudoClass("low-priority");
table.setRowFactory(tv -> new TableRow<Job>() {
#Override
public void updateItem(Job item, boolean empty) {
super.updateItem(item, empty);
pseudoClassStateChanged(highPriority, item != null && item.getPrioritySetting() == 3);
pseudoClassStateChanged(lowPriority, item != null && item.getPrioritySetting() == 1);
}
});
Then just define whatever style you need in an external CSS file:
.table-row-cell:high-priority {
-fx-background: red ;
}
.table-row-cell:low-priority {
-fx-background: green ;
}
Here is an SSCCE
import java.util.List;
import java.util.Random;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.css.PseudoClass;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class TableViewWithPriorityRowColor extends Application {
#Override
public void start(Stage primaryStage) {
TableView<Job> table = new TableView<>();
table.getColumns().add(column("Name", Job::nameProperty));
table.getColumns().add(column("Value", Job::valueProperty));
table.getColumns().add(column("Priority", Job::priorityProperty));
PseudoClass highPriority = PseudoClass.getPseudoClass("high-priority");
PseudoClass lowPriority = PseudoClass.getPseudoClass("low-priority");
table.setRowFactory(tv -> new TableRow<Job>(){
#Override
public void updateItem(Job job, boolean empty) {
super.updateItem(job, empty);
pseudoClassStateChanged(highPriority, job != null && job.getPriority() == 3);
pseudoClassStateChanged(lowPriority, job != null && job.getPriority() == 1);
}
});
table.getItems().addAll(createJobs());
Scene scene = new Scene(new BorderPane(table), 800, 600);
scene.getStylesheets().add("table-view-with-priority.css");
primaryStage.setScene(scene);
primaryStage.show();
}
public List<Job> createJobs() {
Random rng = new Random();
return IntStream.rangeClosed(1, 40)
.mapToObj(i -> new Job("Job "+i, i, rng.nextInt(3) + 1))
.collect(Collectors.toList());
}
public static <S,T> TableColumn<S,T> column(String title, Function<S, ObservableValue<T>> property) {
TableColumn<S,T> col = new TableColumn<>(title);
col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
return col ;
}
public static class Job {
private final StringProperty name = new SimpleStringProperty();
private final IntegerProperty value = new SimpleIntegerProperty();
private final IntegerProperty priority = new SimpleIntegerProperty();
public Job(String name, int value, int priority) {
setName(name);
setValue(value);
setPriority(priority);
}
public final StringProperty nameProperty() {
return this.name;
}
public final String getName() {
return this.nameProperty().get();
}
public final void setName(final String name) {
this.nameProperty().set(name);
}
public final IntegerProperty valueProperty() {
return this.value;
}
public final int getValue() {
return this.valueProperty().get();
}
public final void setValue(final int value) {
this.valueProperty().set(value);
}
public final IntegerProperty priorityProperty() {
return this.priority;
}
public final int getPriority() {
return this.priorityProperty().get();
}
public final void setPriority(final int priority) {
this.priorityProperty().set(priority);
}
}
public static void main(String[] args) {
launch(args);
}
}
with the CSS code shown above in the file table-view-with-priority.css.
Something like Graphviz but more specifically, yFiles.
I want a node/edge type of graph visualization.
I was thinking about making the node a Circle and the edge a Line. The problem is what to use for the area where the nodes/edges appear. Should I use a ScrollPane, a regular Pane, a Canvas, etc...
I will add scrolling functionality, zooming, selecting nodes & dragging nodes.
Thanks for the help.
I had 2 hours to kill, so I thought I'd give it a shot. Turns out that it's easy to come up with a prototype.
Here's what you need:
a main class to use the graph library you create
a graph with a data model
easy adding and removing of nodes and edges (turns out that it's better to name the nodes cells in order to avoid confusion with JavaFX nodes during programming)
a zoomable scrollpane
a layout algorithm for the graph
It's really too much to be asked on SO, so I'll just add the code with a few comments.
The application instantiates the graph, adds cells and connects them via edges.
application/Main.java
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import com.fxgraph.graph.CellType;
import com.fxgraph.graph.Graph;
import com.fxgraph.graph.Model;
import com.fxgraph.layout.base.Layout;
import com.fxgraph.layout.random.RandomLayout;
public class Main extends Application {
Graph graph = new Graph();
#Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
graph = new Graph();
root.setCenter(graph.getScrollPane());
Scene scene = new Scene(root, 1024, 768);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
addGraphComponents();
Layout layout = new RandomLayout(graph);
layout.execute();
}
private void addGraphComponents() {
Model model = graph.getModel();
graph.beginUpdate();
model.addCell("Cell A", CellType.RECTANGLE);
model.addCell("Cell B", CellType.RECTANGLE);
model.addCell("Cell C", CellType.RECTANGLE);
model.addCell("Cell D", CellType.TRIANGLE);
model.addCell("Cell E", CellType.TRIANGLE);
model.addCell("Cell F", CellType.RECTANGLE);
model.addCell("Cell G", CellType.RECTANGLE);
model.addEdge("Cell A", "Cell B");
model.addEdge("Cell A", "Cell C");
model.addEdge("Cell B", "Cell C");
model.addEdge("Cell C", "Cell D");
model.addEdge("Cell B", "Cell E");
model.addEdge("Cell D", "Cell F");
model.addEdge("Cell D", "Cell G");
graph.endUpdate();
}
public static void main(String[] args) {
launch(args);
}
}
The scrollpane should have a white background.
application/application.css
.scroll-pane > .viewport {
-fx-background-color: white;
}
The zoomable scrollpane, I got the code base from pixel duke:
ZoomableScrollPane.java
package com.fxgraph.graph;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.ScrollEvent;
import javafx.scene.transform.Scale;
public class ZoomableScrollPane extends ScrollPane {
Group zoomGroup;
Scale scaleTransform;
Node content;
double scaleValue = 1.0;
double delta = 0.1;
public ZoomableScrollPane(Node content) {
this.content = content;
Group contentGroup = new Group();
zoomGroup = new Group();
contentGroup.getChildren().add(zoomGroup);
zoomGroup.getChildren().add(content);
setContent(contentGroup);
scaleTransform = new Scale(scaleValue, scaleValue, 0, 0);
zoomGroup.getTransforms().add(scaleTransform);
zoomGroup.setOnScroll(new ZoomHandler());
}
public double getScaleValue() {
return scaleValue;
}
public void zoomToActual() {
zoomTo(1.0);
}
public void zoomTo(double scaleValue) {
this.scaleValue = scaleValue;
scaleTransform.setX(scaleValue);
scaleTransform.setY(scaleValue);
}
public void zoomActual() {
scaleValue = 1;
zoomTo(scaleValue);
}
public void zoomOut() {
scaleValue -= delta;
if (Double.compare(scaleValue, 0.1) < 0) {
scaleValue = 0.1;
}
zoomTo(scaleValue);
}
public void zoomIn() {
scaleValue += delta;
if (Double.compare(scaleValue, 10) > 0) {
scaleValue = 10;
}
zoomTo(scaleValue);
}
/**
*
* #param minimizeOnly
* If the content fits already into the viewport, then we don't
* zoom if this parameter is true.
*/
public void zoomToFit(boolean minimizeOnly) {
double scaleX = getViewportBounds().getWidth() / getContent().getBoundsInLocal().getWidth();
double scaleY = getViewportBounds().getHeight() / getContent().getBoundsInLocal().getHeight();
// consider current scale (in content calculation)
scaleX *= scaleValue;
scaleY *= scaleValue;
// distorted zoom: we don't want it => we search the minimum scale
// factor and apply it
double scale = Math.min(scaleX, scaleY);
// check precondition
if (minimizeOnly) {
// check if zoom factor would be an enlargement and if so, just set
// it to 1
if (Double.compare(scale, 1) > 0) {
scale = 1;
}
}
// apply zoom
zoomTo(scale);
}
private class ZoomHandler implements EventHandler<ScrollEvent> {
#Override
public void handle(ScrollEvent scrollEvent) {
// if (scrollEvent.isControlDown())
{
if (scrollEvent.getDeltaY() < 0) {
scaleValue -= delta;
} else {
scaleValue += delta;
}
zoomTo(scaleValue);
scrollEvent.consume();
}
}
}
}
Every cell is represented as Pane into which you can put any Node as view (rectangle, label, imageview, etc)
Cell.java
package com.fxgraph.graph;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.Node;
import javafx.scene.layout.Pane;
public class Cell extends Pane {
String cellId;
List<Cell> children = new ArrayList<>();
List<Cell> parents = new ArrayList<>();
Node view;
public Cell(String cellId) {
this.cellId = cellId;
}
public void addCellChild(Cell cell) {
children.add(cell);
}
public List<Cell> getCellChildren() {
return children;
}
public void addCellParent(Cell cell) {
parents.add(cell);
}
public List<Cell> getCellParents() {
return parents;
}
public void removeCellChild(Cell cell) {
children.remove(cell);
}
public void setView(Node view) {
this.view = view;
getChildren().add(view);
}
public Node getView() {
return this.view;
}
public String getCellId() {
return cellId;
}
}
The cells should be created via some kind of factory, so they are classified by type:
CellType.java
package com.fxgraph.graph;
public enum CellType {
RECTANGLE,
TRIANGLE
;
}
Instantiating them is quite easy:
RectangleCell.java
package com.fxgraph.cells;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import com.fxgraph.graph.Cell;
public class RectangleCell extends Cell {
public RectangleCell( String id) {
super( id);
Rectangle view = new Rectangle( 50,50);
view.setStroke(Color.DODGERBLUE);
view.setFill(Color.DODGERBLUE);
setView( view);
}
}
TriangleCell.java
package com.fxgraph.cells;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import com.fxgraph.graph.Cell;
public class TriangleCell extends Cell {
public TriangleCell( String id) {
super( id);
double width = 50;
double height = 50;
Polygon view = new Polygon( width / 2, 0, width, height, 0, height);
view.setStroke(Color.RED);
view.setFill(Color.RED);
setView( view);
}
}
Then of course you need the edges. You can use any connection you like, even cubic curves. For sake of simplicity I use a line:
Edge.java
package com.fxgraph.graph;
import javafx.scene.Group;
import javafx.scene.shape.Line;
public class Edge extends Group {
protected Cell source;
protected Cell target;
Line line;
public Edge(Cell source, Cell target) {
this.source = source;
this.target = target;
source.addCellChild(target);
target.addCellParent(source);
line = new Line();
line.startXProperty().bind( source.layoutXProperty().add(source.getBoundsInParent().getWidth() / 2.0));
line.startYProperty().bind( source.layoutYProperty().add(source.getBoundsInParent().getHeight() / 2.0));
line.endXProperty().bind( target.layoutXProperty().add( target.getBoundsInParent().getWidth() / 2.0));
line.endYProperty().bind( target.layoutYProperty().add( target.getBoundsInParent().getHeight() / 2.0));
getChildren().add( line);
}
public Cell getSource() {
return source;
}
public Cell getTarget() {
return target;
}
}
An extension to this would be to bind the edge to ports (north/south/east/west) of the cells.
Then you'd want to drag the nodes, so you'd have to add some mouse gestures. The important part is to consider a zoom factor in case the graph canvas is zoomed
MouseGestures.java
package com.fxgraph.graph;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.input.MouseEvent;
public class MouseGestures {
final DragContext dragContext = new DragContext();
Graph graph;
public MouseGestures( Graph graph) {
this.graph = graph;
}
public void makeDraggable( final Node node) {
node.setOnMousePressed(onMousePressedEventHandler);
node.setOnMouseDragged(onMouseDraggedEventHandler);
node.setOnMouseReleased(onMouseReleasedEventHandler);
}
EventHandler<MouseEvent> onMousePressedEventHandler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
Node node = (Node) event.getSource();
double scale = graph.getScale();
dragContext.x = node.getBoundsInParent().getMinX() * scale - event.getScreenX();
dragContext.y = node.getBoundsInParent().getMinY() * scale - event.getScreenY();
}
};
EventHandler<MouseEvent> onMouseDraggedEventHandler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
Node node = (Node) event.getSource();
double offsetX = event.getScreenX() + dragContext.x;
double offsetY = event.getScreenY() + dragContext.y;
// adjust the offset in case we are zoomed
double scale = graph.getScale();
offsetX /= scale;
offsetY /= scale;
node.relocate(offsetX, offsetY);
}
};
EventHandler<MouseEvent> onMouseReleasedEventHandler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
}
};
class DragContext {
double x;
double y;
}
}
Then you need a model in which you store the cells and the edges. Any time new cells can be added and existing ones can be deleted. You need to process them distinguished from the existing ones (e. g. to add mouse gestures, animate them when you add them, etc). When you implement the layout algorithm you'll be faced with the determination of a root node. So you should make an invisible root node (graphParent) which won't be added to the graph itself, but at which all nodes start that don't have a parent.
Model.java
package com.fxgraph.graph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fxgraph.cells.TriangleCell;
import com.fxgraph.cells.RectangleCell;
public class Model {
Cell graphParent;
List<Cell> allCells;
List<Cell> addedCells;
List<Cell> removedCells;
List<Edge> allEdges;
List<Edge> addedEdges;
List<Edge> removedEdges;
Map<String,Cell> cellMap; // <id,cell>
public Model() {
graphParent = new Cell( "_ROOT_");
// clear model, create lists
clear();
}
public void clear() {
allCells = new ArrayList<>();
addedCells = new ArrayList<>();
removedCells = new ArrayList<>();
allEdges = new ArrayList<>();
addedEdges = new ArrayList<>();
removedEdges = new ArrayList<>();
cellMap = new HashMap<>(); // <id,cell>
}
public void clearAddedLists() {
addedCells.clear();
addedEdges.clear();
}
public List<Cell> getAddedCells() {
return addedCells;
}
public List<Cell> getRemovedCells() {
return removedCells;
}
public List<Cell> getAllCells() {
return allCells;
}
public List<Edge> getAddedEdges() {
return addedEdges;
}
public List<Edge> getRemovedEdges() {
return removedEdges;
}
public List<Edge> getAllEdges() {
return allEdges;
}
public void addCell(String id, CellType type) {
switch (type) {
case RECTANGLE:
RectangleCell rectangleCell = new RectangleCell(id);
addCell(rectangleCell);
break;
case TRIANGLE:
TriangleCell circleCell = new TriangleCell(id);
addCell(circleCell);
break;
default:
throw new UnsupportedOperationException("Unsupported type: " + type);
}
}
private void addCell( Cell cell) {
addedCells.add(cell);
cellMap.put( cell.getCellId(), cell);
}
public void addEdge( String sourceId, String targetId) {
Cell sourceCell = cellMap.get( sourceId);
Cell targetCell = cellMap.get( targetId);
Edge edge = new Edge( sourceCell, targetCell);
addedEdges.add( edge);
}
/**
* Attach all cells which don't have a parent to graphParent
* #param cellList
*/
public void attachOrphansToGraphParent( List<Cell> cellList) {
for( Cell cell: cellList) {
if( cell.getCellParents().size() == 0) {
graphParent.addCellChild( cell);
}
}
}
/**
* Remove the graphParent reference if it is set
* #param cellList
*/
public void disconnectFromGraphParent( List<Cell> cellList) {
for( Cell cell: cellList) {
graphParent.removeCellChild( cell);
}
}
public void merge() {
// cells
allCells.addAll( addedCells);
allCells.removeAll( removedCells);
addedCells.clear();
removedCells.clear();
// edges
allEdges.addAll( addedEdges);
allEdges.removeAll( removedEdges);
addedEdges.clear();
removedEdges.clear();
}
}
And then there's the graph itself which contains the zoomable scrollpane, the model, etc. In the graph the added and removed nodes are handled (mouse gestures, cells and edges added to the scrollpane, etc).
Graph.java
package com.fxgraph.graph;
import javafx.scene.Group;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.Pane;
public class Graph {
private Model model;
private Group canvas;
private ZoomableScrollPane scrollPane;
MouseGestures mouseGestures;
/**
* the pane wrapper is necessary or else the scrollpane would always align
* the top-most and left-most child to the top and left eg when you drag the
* top child down, the entire scrollpane would move down
*/
CellLayer cellLayer;
public Graph() {
this.model = new Model();
canvas = new Group();
cellLayer = new CellLayer();
canvas.getChildren().add(cellLayer);
mouseGestures = new MouseGestures(this);
scrollPane = new ZoomableScrollPane(canvas);
scrollPane.setFitToWidth(true);
scrollPane.setFitToHeight(true);
}
public ScrollPane getScrollPane() {
return this.scrollPane;
}
public Pane getCellLayer() {
return this.cellLayer;
}
public Model getModel() {
return model;
}
public void beginUpdate() {
}
public void endUpdate() {
// add components to graph pane
getCellLayer().getChildren().addAll(model.getAddedEdges());
getCellLayer().getChildren().addAll(model.getAddedCells());
// remove components from graph pane
getCellLayer().getChildren().removeAll(model.getRemovedCells());
getCellLayer().getChildren().removeAll(model.getRemovedEdges());
// enable dragging of cells
for (Cell cell : model.getAddedCells()) {
mouseGestures.makeDraggable(cell);
}
// every cell must have a parent, if it doesn't, then the graphParent is
// the parent
getModel().attachOrphansToGraphParent(model.getAddedCells());
// remove reference to graphParent
getModel().disconnectFromGraphParent(model.getRemovedCells());
// merge added & removed cells with all cells
getModel().merge();
}
public double getScale() {
return this.scrollPane.getScaleValue();
}
}
A wrapper for the cell layer. You'll probably want to add multiple layers (e. g. a selection layer which highlights selected cells)
CellLayer.java
package com.fxgraph.graph;
import javafx.scene.layout.Pane;
public class CellLayer extends Pane {
}
Now you need a layout for the cells. I suggest to create a simple abstract class which will get extended as you develop the graph.
package com.fxgraph.layout.base;
public abstract class Layout {
public abstract void execute();
}
For sake of simplicity here's a simple layout algorithm in which random coordinates are used. Of course you'd have to do more complex stuff like tree layouts, etc.
RandomLayout.java
package com.fxgraph.layout.random;
import java.util.List;
import java.util.Random;
import com.fxgraph.graph.Cell;
import com.fxgraph.graph.Graph;
import com.fxgraph.layout.base.Layout;
public class RandomLayout extends Layout {
Graph graph;
Random rnd = new Random();
public RandomLayout(Graph graph) {
this.graph = graph;
}
public void execute() {
List<Cell> cells = graph.getModel().getAllCells();
for (Cell cell : cells) {
double x = rnd.nextDouble() * 500;
double y = rnd.nextDouble() * 500;
cell.relocate(x, y);
}
}
}
The example looks like this:
You can drag the cells with the mouse button and zoom in and out with the mouse wheel.
Adding new cell types is as easy as creating subclasses of Cell:
package com.fxgraph.cells;
import javafx.scene.control.Button;
import com.fxgraph.graph.Cell;
public class ButtonCell extends Cell {
public ButtonCell(String id) {
super(id);
Button view = new Button(id);
setView(view);
}
}
package com.fxgraph.cells;
import javafx.scene.image.ImageView;
import com.fxgraph.graph.Cell;
public class ImageCell extends Cell {
public ImageCell(String id) {
super(id);
ImageView view = new ImageView("http://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Siberischer_tiger_de_edit02.jpg/800px-Siberischer_tiger_de_edit02.jpg");
view.setFitWidth(100);
view.setFitHeight(80);
setView(view);
}
}
package com.fxgraph.cells;
import javafx.scene.control.Label;
import com.fxgraph.graph.Cell;
public class LabelCell extends Cell {
public LabelCell(String id) {
super(id);
Label view = new Label(id);
setView(view);
}
}
package com.fxgraph.cells;
import javafx.scene.control.TitledPane;
import com.fxgraph.graph.Cell;
public class TitledPaneCell extends Cell {
public TitledPaneCell(String id) {
super(id);
TitledPane view = new TitledPane();
view.setPrefSize(100, 80);
setView(view);
}
}
and creating the types
package com.fxgraph.graph;
public enum CellType {
RECTANGLE,
TRIANGLE,
LABEL,
IMAGE,
BUTTON,
TITLEDPANE
;
}
and creating instances depending on the type:
...
public void addCell(String id, CellType type) {
switch (type) {
case RECTANGLE:
RectangleCell rectangleCell = new RectangleCell(id);
addCell(rectangleCell);
break;
case TRIANGLE:
TriangleCell circleCell = new TriangleCell(id);
addCell(circleCell);
break;
case LABEL:
LabelCell labelCell = new LabelCell(id);
addCell(labelCell);
break;
case IMAGE:
ImageCell imageCell = new ImageCell(id);
addCell(imageCell);
break;
case BUTTON:
ButtonCell buttonCell = new ButtonCell(id);
addCell(buttonCell);
break;
case TITLEDPANE:
TitledPaneCell titledPaneCell = new TitledPaneCell(id);
addCell(titledPaneCell);
break;
default:
throw new UnsupportedOperationException("Unsupported type: " + type);
}
}
...
and you'll get this
I had the same problem, I managed to use the javascript vis.js library along with JavaFX WebView.
You can check it out on github if that's useful to someone: https://github.com/arocketman/VisFX
I would give Prefux a try. It is a fork of the Prefuse project.
The original repository starting with JavaFX porting is https://github.com/effrafax/Prefux, but the most maintained fork seems to be the one above (https://github.com/jchildress/Prefux).
Another attempt to port to JavaFX was started at https://github.com/gedeffe/Prefuse, but it is not active anymore.
You can use jfreechart api for generating graph visualization
It provides, Line , Pie, bars. and it is very eary to use.