javafx: display hyperlink in table cell - javafx

I am new to JAVAFX and am trying to display the hyperlink in table cell. I could able to display as a hyperlink but not able to open the link.
Please find the logic for the same.
Main method goes here::
public class Main extends Application {
private BorderPane root;
private TableView<Item> table;
private Scene scene;
private TableColumn<Item, String> nameColumn;
private TableColumn<Item, Hyperlink> urlColumn;
private ObservableList<Item> websiteList;
#Override
public void start(Stage primaryStage) {
root = new BorderPane();
//scene = new Scene(root, 400, 400);
table = new TableView<Item>();
//root.setCenter(table);
nameColumn = new TableColumn<>("Name");
nameColumn.setCellValueFactory(new PropertyValueFactory<>("websiteName"));
urlColumn = new TableColumn<>("Address");
urlColumn.setCellValueFactory(new PropertyValueFactory<>("hyperlink"));
urlColumn.setCellFactory(new HyperlinkCell());
table.getColumns().add(nameColumn);
table.getColumns().add(urlColumn);
websiteList = FXCollections.observableArrayList();
websiteList.add(new Item("Google", "https://www.google.co.in/"));
websiteList.add(new Item("Facebook", "www.facebook.com"));
websiteList.add(new Item("Superglobals", "www.superglobals.net"));
Hyperlink hyperlink = new Hyperlink("Go to Eclipse home page");
hyperlink.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
getHostServices().showDocument("https://www.google.co.in/");
}
});
root.getChildren().addAll(hyperlink);
// root.setBottom(hyperlink);
table.setItems(websiteList);
root.setCenter(table);
scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Item.java::
public class Item {
private String websiteName;
private Hyperlink hyperlink;
public Item(String websiteName, String websiteUrl) {
this.websiteName = websiteName;
this.hyperlink = new Hyperlink(websiteUrl);
}
public String getWebsiteName() {
return websiteName;
}
public void setWebsiteName(String websiteName) {
this.websiteName = websiteName;
}
public Hyperlink getHyperlink() {
return hyperlink;
}
public void setHyperlink(String websiteUrl) {
this.hyperlink = new Hyperlink(websiteUrl);
}
}
HyperlinkCell.java::
public class HyperlinkCell implements Callback<TableColumn<Item, Hyperlink>, TableCell<Item, Hyperlink>> {
private static HostServices hostServices ;
public static HostServices getHostServices() {
return hostServices ;
}
#Override
public TableCell<Item, Hyperlink> call(TableColumn<Item, Hyperlink> arg) {
TableCell<Item, Hyperlink> cell = new TableCell<Item, Hyperlink>() {
#Override
protected void updateItem(Hyperlink item, boolean empty) {
super.updateItem(item, empty);
setGraphic(empty ? null : item);
}
};
return cell;
}
}
Output is displaying like this but am not able to open the hyperlink. Please help us on this.
Thanks.

Just update the onAction handler of the hyperlink in the updateItem() method:
TableCell<Item, Hyperlink> cell = new TableCell<Item, Hyperlink>() {
#Override
protected void updateItem(Hyperlink item, boolean empty) {
super.updateItem(item, empty);
setGraphic(empty ? null : item);
if (! empty) {
item.setOnAction(e -> {
// handle event here...
});
}
}
};
Note that it's really not a good idea to use UI elements (such as Hyperlink) in your data classes (such as Item). I recommend you refactor this so that Item only holds the data:
public class Item {
private String websiteName;
private String url;
public Item(String websiteName, String websiteUrl) {
this.websiteName = websiteName;
this.url = websiteUrl;
}
public String getWebsiteName() {
return websiteName;
}
public void setWebsiteName(String websiteName) {
this.websiteName = websiteName;
}
public String getUrl() {
return url;
}
public void setUrl(String websiteUrl) {
this.url = websiteUrl;
}
}
And then:
private TableColumn<Item, String> urlColumn;
// ...
urlColumn = new TableColumn<>("Address");
urlColumn.setCellValueFactory(new PropertyValueFactory<>("url"));
urlColumn.setCellFactory(new HyperlinkCell());
Somewhere in start() you need to do
HyperlinkCell.setHostServices(getHostServices());
and finally define the Hyperlink in the cell. That way there is only one Hyperlink instance per cell, instead of one for every item in the table.
public class HyperlinkCell implements Callback<TableColumn<Item, Hyperlink>, TableCell<Item, Hyperlink>> {
private static HostServices hostServices ;
public static HostServices getHostServices() {
return hostServices ;
}
public static void setHostServices(HostServices hostServices) {
HyperlinkCell.hostServices = hostServices ;
}
#Override
public TableCell<Item, String> call(TableColumn<Item, String> arg) {
TableCell<Item, Hyperlink> cell = new TableCell<Item, Hyperlink>() {
private final Hyperlink hyperlink = new Hyperlink();
{
hyperlink.setOnAction(event -> {
String url = getItem();
hostServices.showDocument(url);
});
}
#Override
protected void updateItem(String url, boolean empty) {
super.updateItem(url, empty);
if (empty) {
setGraphic(null);
} else {
hyperlink.setText(url);
setGraphic(hyperlink);
}
}
};
return cell;
}
}

Related

JavaFX add/remove button in TableView cell based on row value

This code has a TavbleView in it, the final column has buttons to act on the column, view & clear. the clear button should only be present or enabled (either would be fine) if the given row is in a known state. Here is the code to always display both buttons, it is coded right now that when the "canClear" property is false, no action is taken:
private void addActionsToTable() {
TableColumn<searchResults, Void> actionColumn = new TableColumn("Action");
actionColumn.setCellFactory(col -> new TableCell<searchResults, Void>() {
private final HBox container;
{
Button viewBtn = new Button("View");
Button clearBtn = new Button("Clear");
viewBtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
searchResults data = getTableView().getItems().get(getIndex());
gotoView(data.getLogNo());
}
});
clearBtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
searchResults data = getTableView().getItems().get(getIndex());
String logNo = data.getLogNo();
String serialNumber = data.getSerial();
Boolean canClear = data.getCanClear();
if(canClear)
{
// Take action that has been cut for simplicity
}
}
});
container = new HBox(5, viewBtn, clearBtn);
}
#Override
public void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
setGraphic(container);
}
}
});
SearchTable.getColumns().add(actionColumn);
actionColumn.setPrefWidth(175);
}
What need to happen so that the Clear button is either disabled or not displayed when data.getCanClear() is false?
Assuming your searchResults (sic) class has a BooleanProperty canClearProperty() method:
actionColumn.setCellFactory(col -> new TableCell<searchResults, Void>() {
private final HBox container;
private final Button clearButton ;
{
Button viewBtn = new Button("View");
clearBtn = new Button("Clear");
viewBtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
searchResults data = getTableView().getItems().get(getIndex());
gotoView(data.getLogNo());
}
});
clearBtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
searchResults data = getTableView().getItems().get(getIndex());
String logNo = data.getLogNo();
String serialNumber = data.getSerial();
Boolean canClear = data.getCanClear();
if(canClear)
{
// Take action that has been cut for simplicity
}
}
});
container = new HBox(5, viewBtn, clearBtn);
}
#Override
public void updateItem(Void item, boolean empty) {
clearButton.disableProperty().unbind();
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
clearButton.disableProperty().bind(
getTableView().getItems().get(getIndex())
.canClearProperty().not());
setGraphic(container);
}
}
});

Create Nodes within Loop

Note: this is an updatet version of the initial question.
Whats now beeing asked is how I can get access to the values of a certain row for calculations purposes. For example how can I calculate the difference betweeen values of the expensesColumn and the earningsColumn? (Because there was to much code within my questions, I deleted most of the imports)
package application;
import javafx.application.Application;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {Table.create(primaryStage);}
catch(Exception e) {e.printStackTrace();}
}
public static void main(String[] args) {
launch(args);
}
}
package application;
public class UserJava {
private String member;
private double expenses;
private double earnings;
//Getter und Setter
public String getMember() {
return member;
}
public void setMember(String member) {
this.member = member;
}
public double getExpenses() {
return expenses;
}
public void setExpenses(double expenses) {
this.expenses = expenses;
}
public double getEarnings() {
return earnings;
}
public void setEarnings(double earnings) {
this.earnings = earnings;
}
}
package application;
import javafx.stage.Stage;
public class Table {
static TableView<UserJava> table;
public static void create (Stage primaryStage){
try {
GridPane primarygridpane = new GridPane();
HBox hboxTable = new HBox(10);
//Definition der Tabelle
TableColumn<UserJava, String> userColumn = new TableColumn<>("Name");
userColumn.setCellValueFactory(new PropertyValueFactory<>("member"));
userColumn.setMinWidth(200);
TableColumn<UserJava, Double> expensesColumn = new TableColumn<>("Ausgaben");
expensesColumn.setCellValueFactory(new PropertyValueFactory<>("expenses"));
expensesColumn.setMinWidth(100);
TableColumn<UserJava, Double> earningsColumn = new TableColumn<>("Pfand");
earningsColumn.setCellValueFactory(new PropertyValueFactory<>("earnings"));
earningsColumn.setMinWidth(100);
table = new TableView<>();
table.getColumns().addAll(userColumn, expensesColumn, earningsColumn);
TextField tfMember = new TextField();
tfMember.setMinWidth(200);
tfMember.setPromptText("Name");
TextField tfExpenses = new TextField();
tfExpenses.setMinWidth(100);
tfExpenses.setPromptText("Ausgaben");
TextField tfEarnings = new TextField();
tfEarnings.setMinWidth(100);
tfEarnings.setPromptText("Pfand");
Button btnAdd = new Button("Hinzufügen");
Button btnDelete = new Button("Löschen");
hboxTable.getChildren().addAll(tfMember, tfExpenses, tfEarnings, btnAdd, btnDelete);
table.setEditable(true);
userColumn.setCellFactory(TextFieldTableCell.forTableColumn());
// table.setItems(getUser());
//Sonstiges
Scene scene = new Scene(primarygridpane,725,400);
Text titel = new Text("Application");
titel.setFont(Font.font("Arial", FontWeight.BOLD, 28));
primarygridpane.add(titel, 0, 0, 2, 1);
primarygridpane.add(table, 0, 2);
primarygridpane.add(hboxTable, 0, 3);
// scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
//Funktionen
btnAdd.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e) {
try {
UserJava user = new UserJava();
user.setMember(tfMember.getText());
user.setExpenses(Double.parseDouble(tfExpenses.getText()));
user.setEarnings(Double.parseDouble(tfEarnings.getText()));
table.getItems().add(user);
tfMember.clear();
tfExpenses.clear();
tfEarnings.clear();
System.out.println(table.getItems());
}
catch (NumberFormatException Ausnahme) {}
}
});
btnDelete.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e) {
try {
ObservableList<UserJava> userSelected, userAll;
userAll = table.getItems();
userSelected = table.getSelectionModel().getSelectedItems();
userSelected.forEach(userAll::remove);
System.out.println();
}
catch (java.util.NoSuchElementException Ausnahme) {}
}
});
}
catch (Exception e) {e.printStackTrace();}
}
public ObservableList<UserJava> getUser(){
ObservableList<UserJava> user = FXCollections.observableArrayList();
user.add(new UserJava());
return user;
}
public void changeCell(CellEditEvent<?, ?> ediditedCell) {
UserJava personSelected = table.getSelectionModel().getSelectedItem();
personSelected.setMember(ediditedCell.getNewValue().toString());
}
}

JavaFX TableView custom header

i am customizing JavaFX TableView's header.
therefore i add a Graphic to the Label. By clicking the Label of the header i toggle my custom header(two lined). all this is working fine.
The header gets automatically resized so the custom headerfits in.
BUT, when i hide my custom headerthe headerstays large.
What am i missing so the headershrinks again?
i created a MCVE to demonstrate my problem:
public class TableViewHeaderMCVE extends Application {
private final TableView<Person> table = new TableView<>();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
final VBox root = new VBox();
Scene scene = new Scene(root);
stage.setWidth(218);
stage.setHeight(216);
TableColumn colName = new TableColumn("name");
colName.setMinWidth(100);
colName.setSortable(false);
TableColumn colProfession = new TableColumn("profession");
colProfession.setMinWidth(100);
colProfession.setSortable(false);
table.getColumns().addAll(colName, colProfession);
root.getChildren().addAll(table);
stage.setScene(scene);
stage.show();
// apply this after show!
TableViewHeader.installMod(table);
}
public static class TableViewHeader {
public static void installMod(TableView table) {
for (Node n : table.lookupAll(".column-header > .label")) {
if (n instanceof Label) {
new CustomHeaderLabel((Label) n);
}
}
}
}
public static class CustomHeaderLabel extends BorderPane {
protected Label customNode = null;
BooleanProperty expanded = new SimpleBooleanProperty(this, "expanded", false);
public CustomHeaderLabel(final Label parent) {
Label label = new Label(parent.getText());
// custom MenuButton
Button btn = new Button();
btn.setGraphic(new Label("\u2261"));
btn.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent ae) {
System.out.println("Hello World");
}
});
TextField filterTextField = new TextField();
filterTextField.promptTextProperty().set("type here to filter");
setCenter(label);
setRight(btn);
setBottom(filterTextField);
EventHandler<MouseEvent> toggleHeader = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent me) {
expanded.set(!expanded.get());
}
};
parent.setOnMouseClicked(toggleHeader);
expanded.addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> obs, Boolean oldValue, Boolean value) {
showCustomHeader(value);
}
});
label.textProperty().bind(parent.textProperty());
parent.setGraphic(this);
customNode = parent;
showCustomHeader(expanded.get());
}
protected void showCustomHeader(Boolean value) {
if (value) {
customNode.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
} else {
customNode.setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}
}
public static class Person {
private final SimpleStringProperty name;
private final SimpleStringProperty profession;
private Person(String name, String profession) {
this.name = new SimpleStringProperty(name);
this.profession = new SimpleStringProperty(profession);
}
public String getName() {
return name.get();
}
public String getProfession() {
return profession.get();
}
}
}
thanks to #James_D for his reply.
after his reply i tested the code on another computer
works on:
JDK 1.8.0_161 on Windows 10
JDK 9.0.4 and JDK 10 on Mac OS X
fails on:
JDK 1.8.0_66-b18 on Windows 7

JavaFX StackPane/group prevents me from resizing screen

I cant get this to resize, it always go for the preferred size for each screen. This is not ideal for a full screen application. It bascially just becomes a little box in the top left corner =(
I've spent days on this now but cant get it to work.
Could anyone tell me what im doing wrong? thanks
Main class:
public class Main extends Application {
public static final String MAIN_SCREEN = "main";
public static final String MAIN_SCREEN_FXML = "../gui/main.fxml";
public static final String CUSTOMER_SCREEN = "customer_main";
public static final String CUSTOMER_SCREEN_FXML = "../gui/customer_main.fxml";
#Override
public void start(Stage primaryStage) {
primaryStage.setFullScreen(true);
primaryStage.centerOnScreen();
ScreensController mainContainer = new ScreensController();
mainContainer.loadScreen(Main.MAIN_SCREEN,
Main.MAIN_SCREEN_FXML);
mainContainer.loadScreen(Main.CUSTOMER_SCREEN,
Main.CUSTOMER_SCREEN_FXML);
mainContainer.setScreen(Main.MAIN_SCREEN);
Group root = new Group();
root.getChildren().addAll(mainContainer);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
mainContainer.requestLayout();
}
public static void main(String[] args) {
launch(args);
}
First screen controller class (has FXML file):
public class MainScreenController implements ControlledScreen, Initializable{
ScreensController myController;
#FXML
private VBox mainScreen;
#FXML
private void mainScreenClicked(){
myController.setScreen(Main.CUSTOMER_SCREEN);
}
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
}
#Override
public void setScreenParent(ScreensController screenParent) {
myController = screenParent;
}
Stack pane for a nice layout:
public class ScreensController extends StackPane {
public ScreensController(){
}
private HashMap<String, Node> screens = new HashMap<>();
public void addScreen(String name, Node screen) {
screens.put(name, screen);
}
public boolean loadScreen(String name, String resource) {
try {
FXMLLoader myLoader = new FXMLLoader(getClass().getResource(resource));
Parent loadScreen = (Parent) myLoader.load();
ControlledScreen myScreenControler =
((ControlledScreen) myLoader.getController());
myScreenControler.setScreenParent(this);
addScreen(name, loadScreen);
return true;
}catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
return false;
}
}
public boolean setScreen(final String name) {
if(screens.get(name) != null) { //screen loaded
final DoubleProperty opacity = opacityProperty();
//Is there is more than one screen
if(!getChildren().isEmpty()){
Timeline fade = new Timeline(
new KeyFrame(Duration.ZERO,
new KeyValue(opacity,1.0)),
new KeyFrame(new Duration(1000),
new EventHandler() {
#Override
public void handle(Event t) {
//remove displayed screen
getChildren().remove(0);
//add new screen
getChildren().add(0, screens.get(name));
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO,
new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(800),
new KeyValue(opacity, 1.0)));
fadeIn.play();
}
}, new KeyValue(opacity, 0.0)));
fade.play();
} else {
//no one else been displayed, then just show
setOpacity(0.0);
getChildren().add(screens.get(name));
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO,
new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(2500),
new KeyValue(opacity, 1.0)));
fadeIn.play();
}
return true;
} else {
System.out.println("screen hasn't been loaded!\n");
return false;
}
}
public boolean unloadScreen(String name) {
if(screens.remove(name) == null) {
System.out.println("Screen didn't exist");
return false;
} else {
return true;
}
}
}
interface so that each screen knows its parent:
public interface ControlledScreen {
public void setScreenParent(ScreensController screenPage);
}
Second controller class to verify that the stackpane works (has FXML file):
public class CustomerMenuController implements ControlledScreen, Initializable {
ScreensController myController;
#FXML
private FlowPane customerMenuFlow;
#Override
public void initialize(URL location, ResourceBundle resources) {
for (int i = 0; i < 3;i++){
new Customer();
}
Button [] menuButtons = new Button[Customer.customers.size()];
for (int i = 0; i < Customer.customers.size();i++){
menuButtons[i] = new Button("Customer " + i);
customerMenuFlow.getChildren().add(menuButtons[i]);
}
}
#Override
public void setScreenParent(ScreensController screenParent) {
myController = screenParent;
}
}
You shouldn't use primaryStage.setFullScreen(true); for resizable applications. Not in this context anyway. Once you remove that line, the application will start with its preferred size, but then the user is able to drag the corners of the window to resize the application.

editable table in javafx

I'm trying to build a billing system in javafx, and I could build the table and everything. Now I want to change it, I want the table to be already editable, i.e the text fields in the table should be enabled to edit before onEditCommite. Also storing the data in the table is also giving a problem.
The code is given below. In the below code, the rows are being added and can be deleted. But I want to make it editable when the "new bill" button in clicked. Also any method to calculate the Price by multiplying the this.rate and this.qty.
public class abc extends Application {
private TableView<Billing> table = new TableView<Billing>();
private final ObservableList<Billing> data = FXCollections.observableArrayList();
final HBox hb = new HBox();
final HBox hb1=new HBox();
final HBox hb2= new HBox();
private IntegerProperty index = new SimpleIntegerProperty();
public static void main(String[] args) {
launch(args); }
// Stage Start method. Whole Stage.
#Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setTitle("Billing");
stage.setWidth(550);
stage.setHeight(650);
final Label label = new Label("Billing Trial 2 ");
label.setFont(new Font("Comic Sans", 26));
//Call EditingCell and set true to make it editable
table.setEditable(true);
Callback<TableColumn, TableCell> cellFactory =
new Callback<TableColumn, TableCell>() {
public TableCell call(TableColumn p) {
return new EditingCell();
}
};
TableColumn srnoCol = new TableColumn("Sr. No. ");
srnoCol.setMinWidth(50);
srnoCol.setCellValueFactory(
new PropertyValueFactory<Billing, String>("srNo"));
srnoCol.setCellFactory(cellFactory);
TableColumn numCol = new TableColumn("Item Code ");
numCol.setMinWidth(50);
numCol.setCellValueFactory(
new PropertyValueFactory<Billing, String>("itemCode"));
numCol.setCellFactory(cellFactory);
numCol.setOnEditCommit(
new EventHandler<CellEditEvent<Billing, String>>() {
#Override
public void handle(CellEditEvent<Billing, String> t) {
((Billing) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setItemCode(t.getNewValue());
}
}
);
TableColumn nameCol = new TableColumn("Item Name ");
nameCol.setMinWidth(100);
nameCol.setCellValueFactory(
new PropertyValueFactory<Billing, String>("itemName"));
nameCol.setCellFactory(cellFactory);
nameCol.setOnEditCommit(
new EventHandler<CellEditEvent<Billing, String>>() {
#Override
public void handle(CellEditEvent<Billing, String> t) {
((Billing) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setItemName(t.getNewValue());
}
}
);
TableColumn qtyCol = new TableColumn("Qty ");
qtyCol.setMinWidth(100);
qtyCol.setCellValueFactory(
new PropertyValueFactory<Billing, String>("itemQty"));
qtyCol.setCellFactory(cellFactory);
qtyCol.setOnEditCommit(
new EventHandler<CellEditEvent<Billing, String>>() {
#Override
public void handle(CellEditEvent<Billing, String> t) {
((Billing) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setItemQty(t.getNewValue());
}
}
);
TableColumn rateCol = new TableColumn("Item Rate ");
rateCol.setMinWidth(50);
rateCol.setCellValueFactory(
new PropertyValueFactory<Billing, String>("itemRate"));
rateCol.setCellFactory(cellFactory);
rateCol.setOnEditCommit(
new EventHandler<CellEditEvent<Billing, String>>() {
#Override
public void handle(CellEditEvent<Billing, String> t) {
((Billing) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setItemRate(t.getNewValue());
}
}
);
TableColumn priceCol = new TableColumn("Item Price ");
priceCol.setMinWidth(50);
priceCol.setCellValueFactory(
new PropertyValueFactory<Billing, String>("itemPrice"));
priceCol.setCellFactory(cellFactory);
priceCol.setOnEditCommit(
new EventHandler<CellEditEvent<Billing, String>>() {
#Override
public void handle(CellEditEvent<Billing, String> t) {
((Billing) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setItemPrice(t.getNewValue());
}
}
);
table.setItems(data);
//indexing of elements for deleting function.
table.getSelectionModel().selectedItemProperty().addListener(newChangeListener<Object>() {
#Override
public void changed(ObservableValue<?>observable, Object oldvalue, Object newValue){
index.set(data.indexOf(newValue));
System.out.println("index: "+data.indexOf(newValue));
}
});
//Deleting
final Button deleteButton=new Button("Delete");
deleteButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent de){
int i = index.get();
if (i>-1){
data.remove(i);
table.getSelectionModel().clearSelection();
}
}
});
TableColumn amount = new TableColumn("Amount");
amount.getColumns().addAll(rateCol, priceCol);
table.setItems(data);
table.getColumns().addAll(srnoCol, numCol, nameCol, qtyCol, amount );
//add bill
final Button addButton = new Button("New Bill");
addButton.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent ae)
{
EditingCell ec = new EditingCell();
ec.getString();
ec.createTextField();
table.setEditable(true);
Callback<TableColumn, TableCell> cellFactory =
new Callback<TableColumn, TableCell>() {
public TableCell call(TableColumn p) {
return new EditingCell();
}
};
ec.startEdit();
ec.cancelEdit();
data.add(new Billing(null,null,null,null,null,null));
}
});
hb.getChildren().addAll( addButton, deleteButton);
hb.setAlignment(Pos.BASELINE_LEFT);
hb.setSpacing(16);
final Label label2 = new Label();
label2.setAlignment(Pos.BASELINE_RIGHT);
final VBox vbox = new VBox();
vbox.setSpacing(15);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label,hb2, hb, table,hb1);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
//Class Billing
public static class Billing {
private final SimpleStringProperty itemSrNo;
private final SimpleStringProperty itemCode;
private final SimpleStringProperty itemName;
private final SimpleStringProperty itemQty;
private final SimpleStringProperty itemRate;
private final SimpleStringProperty itemPrice;
private Billing(String iSrNo, String iCode, String iName, String iQty, String iRate,String iPrice)
{
this.itemSrNo = new SimpleStringProperty(iSrNo);
this.itemCode = new SimpleStringProperty(iCode);
this.itemName = new SimpleStringProperty(iName);
this.itemPrice = new SimpleStringProperty(iPrice);
this.itemQty = new SimpleStringProperty(iQty);
this.itemRate = new SimpleStringProperty(iRate);
}
public String getItemSrNo() {
return itemSrNo.get();
}
public void setItemSrNo(String iSrNo) {
itemSrNo.set(iSrNo);
}
public String getItemCode() {
return itemCode.get();
}
public void setItemCode(String iCode) {
itemCode.set(iCode);
}
public String getItemName() {
return itemName.get();
}
public void setItemName(String iName) {
itemName.set(iName);
}
public String getItemQty() {
return itemQty.get();
}
public void setItemQty(String iQty) {
itemQty.set(iQty);
}
public String getItemPrice() {
return itemPrice.get();
}
public void setItemPrice(String iPrice) {
itemPrice.set(iPrice);
}
public String getItemRate() {
return itemRate.get();
}
public void setItemRate(String iRate) {
itemRate.set(iRate);
}
}
//CellEditing
public class EditingCell extends TableCell<Billing, String> {
private TextField textField;
public EditingCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
}
else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
}
else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(new ChangeListener<Boolean>(){
#Override
public void changed(ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) {
if (!arg2) {
commitEdit(textField.getText());
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
}
// calculation of Qty x Rate.
class Calculate {
public String sum(int iQty, int iRate)
{
int sum = iQty*iRate;
String s =""+sum;
return s;
}
}
Old question but here is what I think should work : Dont use setGraphic(null) in your cellFactory. Always set it to TextField. Also for the calculation part you can add listeners to your properties in the data model and perform calculation on any change of values for those properties.

Resources