Toggle adapter for TitledPane - javafx

In my application, I want to apply the behavior of a ToggleGroup to a group of TitledPanes. To do so, I implemented this:
ToggleAdapter.java
package sample;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;
import javafx.scene.control.TitledPane;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
public class ToggleAdapter implements Toggle {
final private TitledPane titledPane;
final private ObjectProperty<ToggleGroup> toggleGroupProperty = new SimpleObjectProperty<>();
private ToggleAdapter(TitledPane titledPane) {
this.titledPane = titledPane;
}
#Override
public ToggleGroup getToggleGroup() {
return toggleGroupProperty.get();
}
#Override
public void setToggleGroup(ToggleGroup toggleGroup) {
toggleGroupProperty.set(toggleGroup);
}
#Override
public ObjectProperty<ToggleGroup> toggleGroupProperty() {
return toggleGroupProperty;
}
#Override
public boolean isSelected() {
return titledPane.isExpanded();
}
#Override
public void setSelected(boolean selected) {
titledPane.setExpanded(selected);
}
#Override
public BooleanProperty selectedProperty() {
return titledPane.expandedProperty();
}
#Override
public Object getUserData() {
return titledPane.getUserData();
}
#Override
public void setUserData(Object value) {
titledPane.setUserData(value);
}
#Override
public ObservableMap<Object, Object> getProperties() {
return FXCollections.emptyObservableMap();
}
public static Toggle asToggle(final TitledPane titledPane) {
return new ToggleAdapter(titledPane);
}
}
sample.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.TitledPane?>
<?import javafx.scene.layout.VBox?>
<VBox spacing="7.0" xmlns="http://javafx.com/javafx/15.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<children>
<TitledPane fx:id="titledPane1" text="Title 1">
<content>
<TextArea minHeight="-Infinity" prefHeight="125.0" prefRowCount="1" wrapText="true" />
</content>
</TitledPane>
<TextField />
<TitledPane fx:id="titledPane2" expanded="false" text="Title 2">
<content>
<TextArea minHeight="-Infinity" prefHeight="125.0" prefRowCount="1" wrapText="true" />
</content>
</TitledPane>
<TitledPane fx:id="titledPane3" expanded="false" text="Title 3">
<content>
<TextArea minHeight="-Infinity" prefHeight="125.0" prefRowCount="1" wrapText="true" />
</content>
</TitledPane>
</children>
<padding>
<Insets bottom="14.0" left="14.0" right="14.0" top="14.0" />
</padding>
</VBox>
Controller.java
package sample;
import javafx.fxml.FXML;
import javafx.scene.control.TitledPane;
import javafx.scene.control.ToggleGroup;
public class Controller {
#FXML private TitledPane titledPane1;
#FXML private TitledPane titledPane2;
#FXML private TitledPane titledPane3;
#FXML
private void initialize() {
final var toggleGroup = new ToggleGroup();
final var toggle1 = ToggleAdapter.asToggle(titledPane1);
toggle1.setToggleGroup(toggleGroup);
final var toggle2 = ToggleAdapter.asToggle(titledPane2);
toggle2.setToggleGroup(toggleGroup);
final var toggle3 = ToggleAdapter.asToggle(titledPane3);
toggle3.setToggleGroup(toggleGroup);
toggleGroup.selectToggle(toggle1);
}
}
Main.java
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
final Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
My naive approach doesn't work, but I have no idea why not. Any ideas?
EDIT: I am aware of Acordion, but this would not be suitable because I cannot place all three TitledPanes in the same parent container.

First, you're reinventing the wheel. Don't do that; there's already a control, Accordion, that implements exactly what you're trying to do here.
All you need is:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Accordion?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.TitledPane?>
<Accordion expandedPane="${titledPane1}" xmlns="http://javafx.com/javafx/15.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<panes>
<TitledPane fx:id="titledPane1" text="Title 1" expanded="true">
<content>
<TextArea minHeight="-Infinity" prefHeight="125.0" prefRowCount="1" wrapText="true" />
</content>
</TitledPane>
<TitledPane fx:id="titledPane2" expanded="false" text="Title 2">
<content>
<TextArea minHeight="-Infinity" prefHeight="125.0" prefRowCount="1" wrapText="true" />
</content>
</TitledPane>
<TitledPane fx:id="titledPane3" expanded="false" text="Title 3">
<content>
<TextArea minHeight="-Infinity" prefHeight="125.0" prefRowCount="1" wrapText="true" />
</content>
</TitledPane>
</panes>
<padding>
<Insets bottom="14.0" left="14.0" right="14.0" top="14.0" />
</padding>
</Accordion>
and
public class Controller {
#FXML private Accordion accordion ;
#FXML private TitledPane titledPane1;
#FXML private TitledPane titledPane2;
#FXML private TitledPane titledPane3;
#FXML
private void initialize() {
accordion.setExpandedPane(titledPane1);
}
}
The ToggleAdapter is not required.
The reason your code doesn't work is that you're assuming, I think, that the ToggleGroup observes the selected state of each of its toggles and updates the other toggle's state when one is selected. This isn't the case; it's actually the responsibility of the toggle implementation to maintain single selection in its toggle group, if it so desires. You could do this by adding a listener to the selected state in the ToggleAdapter (but again, to emphasize, it's always wrong to reinvent functionality defined in the standard API).
private ToggleAdapter(TitledPane titledPane) {
this.titledPane = titledPane;
selectedProperty().addListener(obs -> {
ToggleGroup tg = getToggleGroup();
if (tg != null) {
if (isSelected()) {
tg.selectToggle(this);
} else if (tg.getSelectedToggle() == this) {
tg.selectToggle(null);
}
}
});
}

Changing the implementation of ToggleAdapter to this actually solves the problem:
package sample;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ObjectPropertyBase;
import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;
import javafx.scene.control.TitledPane;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import java.util.Optional;
public class ToggleAdapter implements Toggle {
final private TitledPane titledPane;
final private ObjectProperty<ToggleGroup> toggleGroupProperty = new ObjectPropertyBase<>() {
private ToggleGroup old;
#Override
protected void invalidated() {
if (old != null) {
old.getToggles().remove(ToggleAdapter.this);
}
old = get();
if (get() != null && get().getToggles().contains(ToggleAdapter.this) == false) {
get().getToggles().add(ToggleAdapter.this);
}
}
#Override
public Object getBean() {
return ToggleAdapter.this;
}
#Override
public String getName() {
return "toggleGroup";
}
};
#Override
public ToggleGroup getToggleGroup() {
return toggleGroupProperty.get();
}
#Override
public void setToggleGroup(ToggleGroup toggleGroup) {
toggleGroupProperty.set(toggleGroup);
}
#Override
public ObjectProperty<ToggleGroup> toggleGroupProperty() {
return toggleGroupProperty;
}
#Override
public boolean isSelected() {
return titledPane.isExpanded();
}
#Override
public void setSelected(boolean selected) {
titledPane.setExpanded(selected);
}
#Override
public BooleanProperty selectedProperty() {
return titledPane.expandedProperty();
}
#Override
public Object getUserData() {
return titledPane.getUserData();
}
#Override
public void setUserData(Object value) {
titledPane.setUserData(value);
}
#Override
public ObservableMap<Object, Object> getProperties() {
return FXCollections.emptyObservableMap();
}
public static Toggle asToggle(final TitledPane titledPane) {
return new ToggleAdapter(titledPane);
}
public ToggleAdapter(TitledPane titledPane) {
this.titledPane = titledPane;
selectedProperty().addListener(obs -> {
Optional.ofNullable(getToggleGroup()).ifPresent(toggleGroup -> {
if (isSelected()) {
toggleGroup.selectToggle(this);
} else if (toggleGroup.getSelectedToggle() == this) {
toggleGroup.selectToggle(null);
}
});
});
}
}
Thank you, +James_D for the idea on how to change the implementation.

Related

How to add TableView footer in JavaFx TableView

I am stuck on how to add table footer or column footer in JavaFX TableView. I am looking to add a TableView which will show purchased items with quantities and sells price in columns and total items count and total sum at the TableView footer. I looked at various resources, but could not find footer property associated with TableView. Any idea how to do it?
Model Class
package javafxapplication8;
public class TestModel {
private String itemName = null;
private int pricePerUnit = 0;
private double quantity = 0.0;
private double amount = 0.0;
public TestModel() {
}
public TestModel(String argitemName, int argpricePerUnit, double argquantity, double argamount) {
itemName = argitemName;
pricePerUnit = argpricePerUnit;
quantity = argquantity;
amount = argamount;
}
public void setItemName(String argitemName) {
itemName = argitemName;
}
public void setPricePerUnit(int argpricePerUnit) {
pricePerUnit = argpricePerUnit;
}
public void setQuantity(double argquantity) {
quantity = argquantity;
}
public void setAmount(double argamount) {
amount = argamount;
}
public String getItemName() {
return itemName;
}
public int getPricePerUnit() {
return pricePerUnit;
}
public double getQuantity() {
return quantity;
}
public double getAmount() {
return amount;
}
#Override
public String toString() {
return this.itemName + "" + this.pricePerUnit + "" + this.quantity + "" + this.amount;
}
}
XML Code
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane id="AnchorPane" fx:id="anchor" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication8.TVCTestModel">
<children>
<VBox prefHeight="564.0" prefWidth="857.0">
<children>
<HBox alignment="BOTTOM_LEFT" prefHeight="100.0" prefWidth="1613.0" spacing="20.0" />
<BorderPane prefHeight="695.0" prefWidth="1618.0">
<center>
<VBox prefHeight="544.0" prefWidth="772.0">
<children>
<HBox prefHeight="65.0" prefWidth="1618.0" />
<HBox prefHeight="426.0" prefWidth="857.0">
<children>
<HBox alignment="CENTER" prefHeight="225.0" prefWidth="857.0">
<children>
<TableView fx:id="myTableView" prefHeight="419.0" prefWidth="816.0">
<columns>
<TableColumn fx:id="itemName" prefWidth="200.0" text="Item Name" />
<TableColumn fx:id="pricePerUnit" prefWidth="200.0" text="Price Per Unit" />
<TableColumn fx:id="quantity" prefWidth="200.0" text="Quantity" />
<TableColumn fx:id="amount" prefWidth="200.0" text="Amount" />
</columns>
</TableView>
</children>
</HBox>
</children>
</HBox>
</children>
</VBox>
</center>
<bottom>
</bottom>
</BorderPane>
</children>
</VBox>
</children>
</AnchorPane>
Controller Class
package javafxapplication8;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
public class TVCTestModel implements Initializable {
#FXML
private TableColumn<TestModel, String> itemName;
#FXML
private TableColumn<TestModel, Integer> pricePerUnit;
#FXML
private TableColumn<TestModel, Double> quantity;
#FXML
private TableColumn<TestModel, Double> amount;
#FXML
private TableView<TestModel> myTableView;
public ObservableList<TestModel> objList = FXCollections.observableArrayList();
#FXML
private AnchorPane anchor;
private static TestModel curTestModel;
#Override
public void initialize(URL url, ResourceBundle rb) {
this.itemName.setCellValueFactory(new PropertyValueFactory<>("itemName"));
this.pricePerUnit.setCellValueFactory(new PropertyValueFactory<>("pricePerUnit"));
this.quantity.setCellValueFactory(new PropertyValueFactory<>("quantity"));
this.amount.setCellValueFactory(new PropertyValueFactory<>("amount"));
objList.add(new TestModel("Item 1", 10, 4, 400));
objList.add(new TestModel("Item 2", 20, 5, 1000));
objList.add(new TestModel("Item 3", 30, 6, 1800));
objList.add(new TestModel("Item 4", 400, 7, 2800));
System.out.println(objList.size());
myTableView.setItems(objList);
}
}
MainMethod Class
package javafxapplication8;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class JavaFXApplication8 extends Application {
#Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("TVCTestModel.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException ex) {
Logger.getLogger(JavaFXApplication8.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
launch(args);
}
}
Your updated question was reopened, and the image provided suggests that, instead of a footer, you want two summary fields. As your table is not editable, a simple approximation is illustrated here—add two labels to the view, and iterate the table's model in the controller to establish the localized result:
TVCTestModel.fxml:
…
<bottom>
<HBox alignment="CENTER_RIGHT" style="-fx-spacing: 5px;">
<children>
<Label fx:id="labelQ"/>
<Label fx:id="labelA"/>
</children>
</HBox>
</bottom>
…
TVCTestModel.java
#FXML private Label labelQ;
#FXML private Label labelA;
#Override
public void initialize(URL url, ResourceBundle rb) {
…
double sumQuantity = 0;
double sumAmout = 0;
for (TestModel o : objList) {
sumQuantity += o.getQuantity();
sumAmout += o.getAmount();
}
labelQ.setText("Quantity: "
+ NumberFormat.getNumberInstance().format(sumQuantity));
labelA.setText("Amount: "
+ NumberFormat.getCurrencyInstance().format(sumAmout));
}
If you later decide to make your table editable, as shown here, you should consider these modifications:
Migrate to observable properties in your model class, as shown here.
Create your ObservableList model with an extractor, as shown here and here; your extractor would include properties for quantity and amount; your controller could then update the summary field in a ListChangeListener.

JavaFX Wrapping an editable TextFieldTableCell

I'm trying to get a TableView TextFieldTableCell to be both wrapping the text and adjusting the cell height and also be editable at the same time.
So i'm able to make it wrapped or editable, but not at the same time.
I have been following this Thread and trying about a 100 different permutations and possibilities. I'm sure it is possible, but i'm reaching full fustration quickly. So any help would be highly appreciated!
I'm using SceneBuilder and importing the handles. MainFX.fxml: -->
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.StackPane?>
<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="wrappingEditableCellProject.Controller">
<children>
<AnchorPane prefHeight="200.0" prefWidth="200.0">
<children>
<TableView fx:id="tableView" prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn fx:id="id" prefWidth="75.0" text="id" />
<TableColumn fx:id="name" prefWidth="75.0" text="name" />
</columns>
</TableView>
</children>
</AnchorPane>
</children>
</StackPane>
My Main class:
package wrappingEditableCellProject;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public static void main (String[] args) {
// TODO Auto-generated method stub
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("MainFX.fxml"));
primaryStage.setTitle("mainFx");
primaryStage.setScene(new Scene(root, 900, 600));
primaryStage.show();
}
}
My data entry class:
package wrappingEditableCellProject;
public class TableEntry {
private int id;
private String name;
public TableEntry (int id, String name){
this.id=id;
this.name=name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My Controller class:
package wrappingEditableCellProject;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.util.converter.IntegerStringConverter;
public class Controller {
#FXML TableView<TableEntry> tableView;
#FXML TableColumn<TableEntry, Integer> id;
#FXML TableColumn<TableEntry, String> name;
private ObservableList<TableEntry> dataList = FXCollections.observableArrayList();
#SuppressWarnings({ "rawtypes", "unchecked" })
public void initialize(){
// Set editable
tableView.setEditable(true);
// Configure columns
id.setCellValueFactory(new PropertyValueFactory<>("id"));
id.setCellFactory(TextFieldTableCell.<TableEntry, Integer>forTableColumn(new IntegerStringConverter()));
id.setStyle("-fx-alignment: CENTER-LEFT;");
id.setEditable(false);
id.setSortable(false);
name.setCellValueFactory(new PropertyValueFactory<>("name"));
name.setCellFactory(WrappingTextFieldTableCell.<TableEntry>forTableColumn());
name.setStyle("-fx-alignment: CENTER-LEFT;");
name.setSortable(false);
name.setOnEditCommit(evt -> {
System.out.println("Edit comitted");
evt.getRowValue().setName(evt.getNewValue());
});
TableColumn[] tableColumns = {id,name};
tableView.getColumns().clear();
tableView.getColumns().addAll(tableColumns);
// add data to the table
dataList.clear();
dataList.add(new TableEntry(1, "Steve Upperton Stevenson"));
dataList.add(new TableEntry(2, "Peter May Parker"));
dataList.add(new TableEntry(3, "Tony Stark the machinist"));
dataList.add(new TableEntry(4, "Pepper Pots the CEO of Stark industies"));
FilteredList<TableEntry> dataFiltered = new FilteredList<>(dataList, b -> true);
SortedList<TableEntry> dataSorted = new SortedList<>(dataFiltered);
dataSorted.comparatorProperty().bind(tableView.comparatorProperty());
tableView.setItems(dataSorted);
}
}
Here is my custom cell class WrappingTextFieldTableCell:
package wrappingEditableCellProject;
import javafx.scene.control.Control;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.text.Text;
import javafx.util.converter.DefaultStringConverter;
public class WrappingTextFieldTableCell<S> extends TextFieldTableCell<S, String> {
private final Text cellText;
public WrappingTextFieldTableCell() {
super(new DefaultStringConverter());
setPrefHeight(Control.USE_COMPUTED_SIZE);
this.cellText = createText();
}
#Override
public void cancelEdit() {
super.cancelEdit();
setGraphic(cellText);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!isEmpty() && !isEditing()) {
setGraphic(cellText);
}
}
private Text createText() {
Text text = new Text();
text.wrappingWidthProperty().bind(widthProperty());
text.textProperty().bind(itemProperty());
return text;
}
}
This solution allows me to edit the cell(I know there are easier ways for this), but the wrapping is not taking.
As mentioned i have tried 100 different ways to approach this challenge, but i think this would be the easiest to relate to for any assistance.
Thanks for any support!

JavaFX with fxml TableView updating some columns but not others [duplicate]

This question already has answers here:
The table cells are empty in my tableview. JavaFX + Scenebuilder
(2 answers)
Closed 4 years ago.
In my application Some of the columns in my table are populating like they should be the columns labeled Name Priority and BurstTime have the correct values being added but for some reason the other two ProcessID and State do not update with the values I am adding to my ArrayList.
It looks like my code should be working can anybody see something I have missed?
Here is my controller
package application;
import java.net.URL;
import java.util.ResourceBundle;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
public class Controller implements Initializable {
private ArrayList<String> buf = new ArrayList<>();
protected ArrayList<PCB> array = new ArrayList<>();
protected ArrayList<Process> arrayP = new ArrayList<>();
ObservableList<Process> processData = FXCollections.observableArrayList();
#FXML
private Button SubmitButton;
#FXML
private Button LoadButton;
#FXML
private TextArea textArea;
#FXML
private TextField inputBox;
#FXML
private TableView<Process> ProcessTable;
#FXML
private TableColumn<Process, String> processIDP;
#FXML
private TableColumn<Process, String> processTypeP;
#FXML
private TableColumn<Process, String> priorityCodeP;
#FXML
private TableColumn<Process, String> burstTimeP;
#FXML
private TableColumn<Process, String> StatusCodeP;
#Override
public void initialize(URL url, ResourceBundle rb) {
processIDP.setCellValueFactory(new PropertyValueFactory<Process, String>("processIDP"));
processTypeP.setCellValueFactory(new PropertyValueFactory<Process, String>("processTypeP"));
priorityCodeP.setCellValueFactory(new PropertyValueFactory<Process, String>("priorityCodeP"));
burstTimeP.setCellValueFactory(new PropertyValueFactory<Process, String>("burstTimeP"));
StatusCodeP.setCellValueFactory(new PropertyValueFactory<Process, String>("StatusCodeP"));
Process p1 = new Process();
p1.setprocessIDP("22");
p1.setProcessTypeP ("Apname");
p1.setPriorityCodeP("1");
p1.setBurstTimeP ("13");
p1.setstatusCodeP("Tada");
arrayP.add(p1);
ProcessTable.getItems().addAll(arrayP.get(0));
ProcessTable.setItems(FXCollections.observableArrayList(arrayP));
Process p2 = new Process();
p2.setprocessIDP("24");
p2.setProcessTypeP ("Bpname");
p2.setBurstTimeP ("15");
p2.setPriorityCodeP("2");
arrayP.add(p2);
ProcessTable.getItems().addAll(arrayP.get(1));
// edit existing cell ?
arrayP.get(1).setPriorityCodeP("8");
arrayP.get(1).setstatusCodeP("This");
arrayP.get(1).setprocessIDP("TEST");
}
public ObservableList<Process> getProcessData() {
return processData;
}
#FXML
private TextField LoadProgram;
#FXML
private void handleButtonAction() {
textArea.appendText(inputBox.getText() + "\n");
StringTokenizer st1 = new StringTokenizer(inputBox.getText(), " ");
switch(st1.nextToken()) {
// case "proc": proc(); break;
case "mem": textArea.appendText("Memory: " + String.valueOf(Memory.getUsedMemory()) + "/" + String.valueOf(Memory.getTotalMemory()) + "\n"); break;
// case "exe": exe(); break;
// case "reset": reset(); break;
case "load": buf.add(inputBox.getText()) ;
// edit existing cell ?
arrayP.get(1).setPriorityCodeP("9");
ProcessTable.refresh();
break;
case "exit": System.exit(0); break;
case "clear": textArea.clear(); break;
default: break;
}
}
#FXML
private void handleLoadAction() {
File infile = new File("files/" + LoadProgram.getText() + ".txt");
if (infile.exists() == true ) {
textArea.appendText("Loading " + LoadProgram.getText() + "\n");
}
//call to read data here
else {
textArea.appendText("No Program named " + LoadProgram.getText() + " found \n");
}}
public class textLine {
private String infile;
private String cmd, value;
private Scanner input;
public void parseFile(String filename) {
this.infile = "files/" + filename + ".txt";
parseFile();
}
public void addbuf(String textline) {
buf.add(textline);
}
private void parseFile() {
buf.clear();
try {
File file = new File(infile);
if (file.exists() == true)
input = new Scanner(file);
while (input.hasNext()) {
buf.add(input.next());
}
} catch (Exception e) {
e.printStackTrace();
}
input.close();
}
}
}
Here is my class for Procsess
package application;
public class Process {
String processTypeP = "";
String priorityCodeP = "0";
int lineCodeP = 0;
String burstTimeP = "0";
String processIDP = "0";
String StatusCodeP = "0";
public Process (){}
public String getProcessTypeP() {
return processTypeP;
}
public void setProcessTypeP(String processTypeP) {
this.processTypeP = processTypeP;
}
public String getPriorityCodeP() {
return priorityCodeP;
}
public void setPriorityCodeP(String priorityCodeP) {
this.priorityCodeP = priorityCodeP;
}
public int getLineCodeP() {
return lineCodeP;
}
public void setLineCodeP(int lineCodeP) {
this.lineCodeP = lineCodeP;
}
public String getBurstTimeP() {
return burstTimeP;
}
public void setBurstTimeP(String burstTimeP) {
this.burstTimeP = burstTimeP;
}
public String getprocessIDP() {
return processIDP;
}
public void setprocessIDP(String processIDP) {
this.processIDP = processIDP;
}
public String getstatusCodeP() {
return StatusCodeP;
}
public void setstatusCodeP(String StatusCodeP) {
this.StatusCodeP = StatusCodeP;
}
}
Here is my main application
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
FXMLLoader loader = new FXMLLoader(Main.class.getResource("/Main.fxml"));
// Parent root = FXMLLoader.load(getClass().getResource("/Main.fxml"));
AnchorPane root = (AnchorPane) loader.load(Main.class.getResource("/application/Main.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
and my fxml file
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Controller">
<children>
<TabPane layoutX="4.0" layoutY="4.0" prefHeight="700.0" prefWidth="900.0" tabClosingPolicy="UNAVAILABLE">
<tabs>
<Tab text="Processes">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
<children>
<TextField fx:id="inputBox" layoutX="14.0" layoutY="54.0" />
<Button fx:id="SubmitButton" layoutX="109.0" layoutY="94.0" mnemonicParsing="false" onAction="#handleButtonAction" text="Submit" />
<TextArea fx:id="textArea" layoutX="197.0" layoutY="14.0" prefHeight="105.0" prefWidth="493.0" />
<TableView fx:id="ProcessTable" layoutX="36.0" layoutY="157.0" prefHeight="430.0" prefWidth="654.0">
<columns>
<TableColumn fx:id="processIDP" prefWidth="75.0" text="ProccessID" />
<TableColumn fx:id="processTypeP" prefWidth="101.0" text="Name" />
<TableColumn fx:id="priorityCodeP" prefWidth="94.0" text="Priority" />
<TableColumn fx:id="StatusCodeP" prefWidth="119.0" text="State" />
<TableColumn fx:id="burstTimeP" prefWidth="100.0" text="BurstTime" />
</columns>
</TableView>
<TextField fx:id="LoadProgram" layoutX="712.0" layoutY="492.0" />
<Button fx:id="LoadProgramButton" layoutX="725.0" layoutY="531.0" mnemonicParsing="false" onAction="#handleLoadAction" text="Load External Program" />
</children></AnchorPane>
</content>
</Tab>
<Tab text="Scheduler">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
</content>
</Tab>
<Tab text="Memory">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0" />
</content>
</Tab>
</tabs>
</TabPane>
</children>
</AnchorPane>
Try renaming your getter methods from getprocessIDP and getstatusCodeP to getProcessIDP and getStatusCodeP respectively (note the capital 'S' and 'P'). To avoid problems like this in the future it's a good habit to generate getters, setters and constructors with the IDE instead of doing it manually.

JavaFX: Strange case with DataView fill operation

I have a very strange problem with my test application. I need to fill the JavaFX TableView element with some data. Here is the code:
fxmldocumentController.java
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TableView; //A
import javafx.scene.control.TableColumn; //B
import javafx.scene.control.cell.PropertyValueFactory; //C
public class fxmldocumentController implements Initializable
{
#FXML
private TableView<employees> mainTableView;
#FXML
private TableColumn<employees, Integer> age;
#FXML
private TableColumn<employees, String> userName, companyName;
#Override
public void initialize(URL url, ResourceBundle rb)
{
// TODO:
mainTableView.getItems().
add(new employees("Yuri P. Bodrov", "VMware", 35));
mainTableView.getItems().
add(new employees("Ivan Y. Bodrov", "VMware", 5));
mainTableView.getItems().
add(new employees("Peter Y. Bodrov", "VMware", 2));
// A problem starts here:
age.setCellValueFactory(new PropertyValueFactory<>("age"));
userName.setCellValueFactory(new PropertyValueFactory<>("userName"));
companyName.
setCellValueFactory(new PropertyValueFactory<>("companyName"));
}
}
fxmldocument.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="300.0" prefWidth="400.0" style="-fx-
background-color: white;"
xmlns="http://javafx.com/javafx/8"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="sampletableviewapp00.fxmldocumentController">
<children>
<Label fx:id="testLabel" layoutX="14.0" layoutY="14.0" style="-fx-
background-color: white;" text="Employees. TableView." textFill="#505050">
<font>
<Font size="14.0" />
</font>
</Label>
<TableView fx:id="mainTableView" layoutX="12.0" layoutY="50.0"
prefHeight="200.0" prefWidth="377.0">
<columns>
<TableColumn prefWidth="90.0" text="UserName" />
<TableColumn prefWidth="119.0" text="CompanyName" />
<TableColumn prefWidth="84.0" text="Age" />
</columns>
</TableView>
</children>
</AnchorPane>
Sampletableviewapp00.java
package sampletableviewapp00;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Sampletableviewapp00 extends Application
{
#Override
public void start(Stage stage) throws Exception
{
Parent root = FXMLLoader.load(getClass().
getClassLoader().getResource("fxmldocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
employees.java
package sampletableviewapp00;
public class employees
{
String userName, companyName;
int age;
// Generate Properties. Getters:
public int GetAge()
{
return age;
}
public String GetUserName()
{
return userName;
}
public String GetCompanyName()
{
return companyName;
}
// Generate Properties. Setters:
public void SetAge(int age)
{
this.age = age;
}
public void SetUserName(String userName)
{
this.userName = userName;
}
public void SetCompanyName(String companyName)
{
this.companyName = companyName;
}
// Generate Constructor of Employees class:
public employees(String userName, String companyName, int age)
{
this.userName = userName;
this.companyName = companyName;
this.age = age;
}
}
When I run this application the NetBeans IDE 8.2 returns this stack of exceptions/errors: see outputError.png as attachment
outputError.png
outputError02.PNG
Dear colleagues! Do you have any ideas to resolve this problem? Could you try to write this code by yourself and run? Thanks in advance! :-)
You have fxmldocument.xml but tried to load "fxmldocument.fxml".
Rename the file to have fxml extension.
Also make sure you put the fxml file under /resources/yourpackagepath/ folder and load as:
Sampletableviewapp00.class.getResource("fxmldocument.fxml")
This line is triggering the exception:
Parent root = FXMLLoader.load(getClass().
getClassLoader().getResource("fxmldocument.fxml"));
Your fxml document's extension is xml in your project and you are trying to load it as .fxml in the above line.
Rename fxmldocument.xml to fxmldocument.fxml.

Is it possible combine fx:include and afterburner

I currently using afterburner.fx to tailor together components of JavaFX based application.
Right now I trying move components in separate fxml files for more comfortable maintenance.
To load such components I using fx:include directive which allow load nested components automatically.
Problem is that with automatic load I loosing possibility get presenter from nested view.
Is there a way to combine automatic load and in same time, be able work with nested components from parent root?
These two seem to work fine together.
Afterburner works by setting a controller factory on the FXML loader, which takes care of instantiating the presenter class and injecting values into it.
The <fx:include> element will propagate the controller factory when loading the included FXML, so you can also inject values into the controller defined in the included FXML. Because afterburner effectively uses a singleton scope for injection, the same instance of injected fields will be used. This means you can readily share your data model between the different presenter classes.
If you want access to the presenter associated with the included FXML, just use the standard technique for "nested controllers".
So, for example:
main.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.cell.PropertyValueFactory?>
<?import javafx.geometry.Insets?>
<BorderPane xmlns:fx="http://javafx.com/fxml" fx:controller="application.MainPresenter">
<center>
<TableView fx:id="table">
<columns>
<TableColumn text="First Name" prefWidth="150">
<cellValueFactory>
<PropertyValueFactory property="firstName" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Last Name" prefWidth="150">
<cellValueFactory>
<PropertyValueFactory property="lastName" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Email" prefWidth="200">
<cellValueFactory>
<PropertyValueFactory property="email" />
</cellValueFactory>
</TableColumn>
</columns>
</TableView>
</center>
<bottom>
<fx:include source="Editor.fxml" fx:id="editor">
<padding>
<Insets top="5" bottom="5" left="5" right="5"/>
</padding>
</fx:include>
</bottom>
</BorderPane>
editor.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.control.Button?>
<GridPane xmlns:fx="http://javafx.com/fxml" hgap="5" vgap="10" fx:controller="application.EditorPresenter">
<Label GridPane.rowIndex="0" GridPane.columnIndex="0" text="First Name:"/>
<TextField fx:id="firstNameTextField" GridPane.rowIndex="0" GridPane.columnIndex="1"/>
<Label GridPane.rowIndex="1" GridPane.columnIndex="0" text="Last Name"/>
<TextField fx:id="lastNameTextField" GridPane.rowIndex="1" GridPane.columnIndex="1"/>
<Label GridPane.rowIndex="2" GridPane.columnIndex="0" text="Email"/>
<TextField fx:id="emailTextField" GridPane.rowIndex="2" GridPane.columnIndex="1"/>
<HBox GridPane.rowIndex="3" GridPane.columnIndex="0" GridPane.columnSpan="2">
<Button fx:id="addEditButton" onAction="#addEdit" />
</HBox>
</GridPane>
MainPresenter.java:
package application;
import javax.inject.Inject;
import javafx.fxml.FXML;
import javafx.scene.control.TableView;
public class MainPresenter {
#FXML
private TableView<Person> table ;
// This is the controller (presenter) for the included fxml
// It is injected by the FXMLLoader; the rule is that "Controller" needs to be
// appended to the fx:id attribute of the <fx:include> tag.
// This is not used in this example but is here to demonstrate how to access it
// if needed.
#FXML
private EditorPresenter editorController ;
#Inject
private DataModel dataModel ;
public void initialize() {
table.setItems(dataModel.getPeople());
table.getSelectionModel().selectedItemProperty().addListener(
(obs, oldPerson, newPerson) -> dataModel.setCurrentPerson(newPerson));
dataModel.currentPersonProperty().addListener((obs, oldPerson, newPerson) -> {
if (newPerson == null) {
table.getSelectionModel().clearSelection();
} else {
table.getSelectionModel().select(newPerson);
}
});
dataModel.getPeople().addAll(
new Person("Jacob", "Smith", "jacob.smith#example.com"),
new Person("Isabella", "Johnson", "isabella.johnson#example.com"),
new Person("Ethan", "Williams", "ethan.williams#example.com"),
new Person("Emma", "Jones", "emma.jones#example.com"),
new Person("Michael", "Brown", "michael.brown#example.com")
);
}
}
EditorPresenter.java:
package application;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javax.inject.Inject;
public class EditorPresenter {
#FXML
private TextField firstNameTextField ;
#FXML
private TextField lastNameTextField ;
#FXML
private TextField emailTextField ;
#FXML
private Button addEditButton ;
#Inject
private DataModel dataModel ;
public void initialize() {
addEditButton.textProperty().bind(
Bindings.when(Bindings.isNull(dataModel.currentPersonProperty()))
.then("Add")
.otherwise("Update")
);
dataModel.currentPersonProperty().addListener((obs, oldPerson, newPerson) -> {
if (newPerson == null) {
firstNameTextField.setText("");
lastNameTextField.setText("");
emailTextField.setText("");
} else {
firstNameTextField.setText(newPerson.getFirstName());
lastNameTextField.setText(newPerson.getLastName());
emailTextField.setText(newPerson.getEmail());
}
});
}
#FXML
private void addEdit() {
Person person = dataModel.getCurrentPerson();
String firstName = firstNameTextField.getText();
String lastName = lastNameTextField.getText();
String email = emailTextField.getText();
if (person == null) {
dataModel.getPeople().add(new Person(firstName, lastName, email));
} else {
person.setFirstName(firstName);
person.setLastName(lastName);
person.setEmail(email);
}
}
}
MainView.java:
package application;
import com.airhacks.afterburner.views.FXMLView;
public class MainView extends FXMLView {
}
Main.java (application class):
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import com.airhacks.afterburner.injection.Injector;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
MainView mainView = new MainView();
Scene scene = new Scene(mainView.getView(), 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
#Override
public void stop() throws Exception {
Injector.forgetAll();
}
public static void main(String[] args) {
launch(args);
}
}
DataModel.java:
package application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class DataModel {
private final ObservableList<Person> people = FXCollections.observableArrayList();
private final ObjectProperty<Person> currentPerson = new SimpleObjectProperty<>(this, "currentPerson");
public ObservableList<Person> getPeople() {
return people ;
}
public final Person getCurrentPerson() {
return currentPerson.get();
}
public final void setCurrentPerson(Person person) {
this.currentPerson.set(person);
}
public ObjectProperty<Person> currentPersonProperty() {
return currentPerson ;
}
}
And the usual Person.java example:
package application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Person {
private final StringProperty firstName = new SimpleStringProperty(this, "firstName");
public final String getFirstName() {
return firstName.get();
}
public final void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public StringProperty firstNameProperty() {
return firstName ;
}
private final StringProperty lastName = new SimpleStringProperty(this, "lastName");
public final String getLastName() {
return lastName.get();
}
public final void setLastName(String lastName) {
this.lastName.set(lastName);
}
public StringProperty lastNameProperty() {
return lastName ;
}
private final StringProperty email = new SimpleStringProperty(this, "email");
public final String getEmail() {
return email.get();
}
public final void setEmail(String email) {
this.email.set(email);
}
public StringProperty emailProperty() {
return email ;
}
public Person(String firstName, String lastName, String email) {
setFirstName(firstName);
setLastName(lastName);
setEmail(email);
}
}

Resources