Bindings.and() in JavaFX not firing? - javafx

On startup my JavaFX app fires off two background tasks, one to initialize the database and the other to authenticate against an email server. Each task has a Boolean property indicating successful completion. Once both of those tasks complete I want to start a third task to start polling for new emails.
I thought I could use javafx.beans.binding.Bindings.and() to combine the result of these two tasks, but it's not firing. Here's some code:
BooleanBinding databaseInitializedProperty = NotesLocalDatabase.initializationStateProperty().isEqualTo( State.SUCCEEDED );
BooleanProperty isLoggedInProperty = loginPanel.isLoggedInProperty();
databaseInitializedProperty.addListener( (value, oldVal, newVal ) -> {
if( newVal ) log.info( "DATABASE INITIALIZED" ); } );
isLoggedInProperty.addListener( (value, oldVal, newVal ) -> {
if( newVal ) log.info( "IS LOGGED IN" ); } );
Bindings.and( databaseInitializedProperty, isLoggedInProperty ).addListener( (value, oldVal, newVal) -> {
log.info( "COMPOUND BINDING CHANGED: " + value + ", " + oldVal + ", " + newVal );
if( newVal ) {
log.info( "Login and database initialization both complete. Starting message check service." );
startUpdates();
}
} );
I know my properties are working correctly because I see both "DATABASE INITIALIZED" and "IS LOGGED IN" in the logs. However, I never see "COMPOUND BINDING CHANGED". From reading the docs I was under the impression that the change listener on Bindings.and() binding be fired whenever either property changes. Is that not the case?

You are running into another version of this: Bidirectional JavaFX Binding is destroyed by unrelated code
The problem is that the result of Bindings.and(...) has gone out of scope by the time the properties change. This makes it eligible for garbage collection. It's not unreasonable to assume your tasks are consuming enough memory to force the garbage collector to run, so the binding gets destroyed.
For a simple example, run the following with and without the call to System.gc();:
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
public class BindingTest {
public static void main(String[] args) {
BooleanProperty x = new SimpleBooleanProperty(false);
BooleanProperty y = new SimpleBooleanProperty(false);
x.addListener((obs, oldX, newX) -> System.out.printf("x changed from %s to %s%n", oldX, newX));
y.addListener((obs, oldY, newY) -> System.out.printf("y changed from %s to %s%n", oldY, newY));
Bindings.and(x, y).addListener((obs, oldXAndY, newXAndY) -> System.out.printf("x&y changed from %s to %s%n", oldXAndY, newXAndY));
x.set(true);
// System.gc();
y.set(true);
}
}
The fix is to force the binding to stay in scope. You may need to (somewhat unnaturally) make it an instance variable somewhere:
public class SomeClass {
private BooleanBinding initializationComplete ;
public void whereverYouHadThisCodeBefore() {
// ..
initializationComplete = Bindings.and(databaseInitializedProperty, isLoggedInProperty);
initializationComplete.addListener(...);
}
}

Related

Multiple chained API calls to fetch data, but doOnNext of PublishSubject is never reached

I have a problem to understand a chained "RXJava-Retrofit" API call. I got inspired by this and implement this class named ObservationLoader to load the data from the API bucket per bucket. When the end of data is reached the API sends a endOfRecords=true:
public Observable<PageObject<Observation>> getAllObservationDataByRegion(long taxonKey,
String regionId) {
final PublishSubject<PageObject<Observation>> subject = PublishSubject.create();
return subject.doOnSubscribe(disposable -> {
this.getData(taxonKey, regionId, 0).subscribe(subject);
})
.doOnNext(observationPageObject -> {
if (observationPageObject.isEndOfRecords()) {
// -> list is completely loaded
subject.onComplete();
} else {
int nextOffset = observationPageObject.getOffset() + 1;
this.getData(taxonKey, regionId, null, nextOffset).subscribe(subject);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
private Observable<PageObject<Observation>> getData(long id,
String regionId,
int offset) {
// Get your API response value
return this.api.getObservations(id, regionId, ObservationLoader.PAGE_LIMIT, offset);
}
In my Android fragment HomeFragment I subscribe to the ObservationLoader:
ObservationLoader loader = new ObservationLoader(this.getApi());
Observable<PageObject<Observation>> observable = loader
.getAllObservationDataByRegion(this.getSelectedSpecies(), this.getSelectedRegion());
observable.subscribe(new Observer<PageObject<Observation>>() {
#Override
public void onSubscribe(Disposable d) {
Log.i(TAG, "ON_SUBSCRIBE");
}
#Override
public void onNext(PageObject<Observation> observationPageObject) {
Log.i(TAG, "ON_NEXT");
}
#Override
public void onError(Throwable e) {
Log.i(TAG, "ERROR = " + e.getMessage());
}
#Override
public void onComplete() {
Log.i(TAG, "COMPLETED");
}
});
I can see that the onSubscribe() and doOnSubscribe() are called and even the getData() is reached. I assume the API is responding correctly (a previous attempt attempt with recursion worked fine). But I never reached the doOnNext function. The observer goes straight to onComplete() and no data is received. What could be the reason?
When doOnSubscribe runs, the doesn't see any consumers yet so if getData is synchronous, there won't be any first results to trigger further results. Also if getData ends, it will complete the setup so the next getData call in doOnNext will push to an already terminated subject, ingoring all data.
You'll need a differently organized feedback loop:
// we loop back the nextOffset, in a thread-safe manner
Subject<Integer> subject = PublishSubject.<Integer>create()
.toSerialized();
// bootstrap with 0 and keep open for more offsets
subject.mergeWith(Observable.just(0))
// get the data for the current offset
.concatMap(nextOffset -> getData(taxonKey, regionId, nextOffset)
.subscribeOn(Schedulers.io())
)
// if the response is end of records, stop
.takeWhile(observationPageObject -> !observationPageObject.isEndOfRecords())
// otherwise not end of records, feedback the new offset
.doOnNext(observationPageObject ->
subject.onNext(observationPageObject.getOffset() + 1)
)
// get the data on the main thread
.observeOn(AndroidSchedulers.mainThread());

Combobox selections disappear when table editing canceled

Ok, I'm starting to lose my mind on this one. I have a tableview where there are 3 combobox table cells. The first is a box where a user can select a job, the job selected changes the next combobox's options (job category). The job category selection changes the options in the labor box. So the flow down is:
job > job category > labor.
I have a very peculiar problem. When editing the table, you can click on any box to get a corresponding list of the available selections based on the other fields. This works fine. Where it blows up is when a selection ISN'T made. To make things more interesting, it only effects the job and job category comboboxes the labor box works flawlessly.
symptom:
-- job category selection disappears when edit is canceled via esc or focus lost
-- selection chosen in the job category field is placed into the job field when editing is canceled via esc or upon loss of focus
Here's the steps to recreate the symptoms:
1) click on job category box and enable editing mode
2) make a new selection from the drop down list
new selection made img
3) click on the job box and enable editing
4) click off the job box and cancel editing by click on job category or labor box in the same row
5) enable job category editing and then cancel job category edit by clicking on either labor / labor boxes or using esc
lose the job category / job selections img
here is the code to initialize the graphic when it comes up:
public void initialize(URL location, ResourceBundle resources) {
/* this is here because the screen handler will load up the Main screen in the
in the hashmap; no connection data will be assigned to the user at that time.
Without this block, when the hashmap attempts to load the Main data this
will cause the screenhandler to error and the main application
to not load correctly. The block below initiatializes the connection to
prevent this from happening.*/
if ( vUsers.getConn() == null){
try {
//establishes a user's connection to the database
vUsers.ConnecrDB();
} catch (SQLException | IOException ex) {
//debugging catch
System.out.println(ex);
}
}
//set the job box list for the user
cmbxJobT.setItems(cmbxPopulator.getJobComboBox());
cmbxJobT.valueProperty().addListener(new ChangeListener<String>(){
#Override
//reads the user's selectino and returns the appropriate labor codes for the Employee
public void changed(ObservableValue o, String oldValue, String newValue){
if (newValue != null){
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().addAll(cmbxPopulator.getJobCatComboBox(newValue));
}else {
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().add(null);
}
}
});
cmbxJobCatT.valueProperty().addListener(new ChangeListener<String>(){
#Override
//reads the user's selectino and returns the appropriate labor codes for the Employee
public void changed(ObservableValue o, String oldValue, String newValue){
if (newValue != null){
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().addAll(cmbxPopulator.getLaborComboBox(newValue));
}else {
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().add(null);
}
}
});
tblviewTime.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSel) ->{
if (newSel != null){
Model_Time current = tblviewTime.getSelectionModel().getSelectedItem();
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().addAll(cmbxPopulator.getJobCatComboBox(current.getJob()));
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().addAll(cmbxPopulator.getLaborComboBox(current.getJobCat()));
}
if (newSel == null){
Model_Time current = tblviewTime.getSelectionModel().getSelectedItem();
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().addAll(cmbxPopulator.getJobCatComboBox(current.getJob()));
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().addAll(cmbxPopulator.getLaborComboBox(current.getJobCat()));
}
});
addDragListeners(bertaTabPane);
}
here's the code that sets up the tableview:
public void btnTimeSearch(ActionEvent event){
//makes an instance of the toolkit needed to query user time.
Database_RetrievesTime userData = new Database_RetrievesTime();
//grabs data from the userinput fields to set the toolkit
userData.setDateSelect(lblPickDateT.getValue());
userData.setJobBoxSelect(jobTbl.getIdByDesc(cmbxJobT.getValue()));
userData.setLaborBoxSelect(laborTbl.getIdByDesc(cmbxLaborT.getValue()));
userData.setJobCatSelect(jobCatTbl.getIdByDesc(cmbxJobCatT.getValue()));
/*creates cell factories in each column and maps the cell values to the
observable array list's IDs. The section also sets the columns up for user
editing to be available and the methods to execute upon an editted cell
being committed to entry.
**NOTE: The values are retrieved by the model class's getter methods.
Changing a name in the model class requires the user to update the getters.
Naming convention does apply. So for example: a variable
named cscHelp is added, it would need to have a getter called getCscHelp otherwise
the corresponding column will return blanks.*/
//setup ID column
IDcol.setCellValueFactory(new PropertyValueFactory<>("ID"));
//setup Datecol
Datecol.setCellValueFactory(new PropertyValueFactory<>("userDate"));
Datecol.setCellFactory(DatePickerTableCell.forTableColumn());
//created a custom datepicker callback that can be reused throughout the code's interfaces
Datecol.setOnEditCommit((CellEditEvent<Model_Time,LocalDate> t) -> {
//generate a temporary variable to convert the LocalDate returned into a SimpleObjectProperty
ObjectProperty<LocalDate> temp = new SimpleObjectProperty(t.getNewValue());
//store the new value to the object's model
t.getRowValue().setUserDate(temp);
//store row's object to the change list
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
//signaling to the program that a change had been made
isChanged = true;
});
//job column setup
Jobcol.setCellValueFactory(new PropertyValueFactory<>("Job"));
Jobcol.setCellFactory(ComboBoxTableCell.forTableColumn(cmbxPopulator.getJobComboBox()));
/*creates a combobox filled with the populated items found at initialization of the screen
user inputs are automatically commited
*/
Jobcol.setOnEditCommit((CellEditEvent<Model_Time,String> t) -> {
SimpleStringProperty ssp = new SimpleStringProperty(t.getNewValue());
//store selection to the object's model (unprocessed so values will show something like '6002: Kobota'
t.getRowValue().setJob(ssp);
//store row's object to the change list
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().addAll(cmbxPopulator.getJobCatComboBox(t.getRowValue().getJob()));
//signaling a change has been made
isChanged = true;
});
jobCatCol.setCellValueFactory(new PropertyValueFactory<>("JobCat"));
jobCatCol.setCellFactory(ComboBoxTableCell.forTableColumn(cmbxPopulator.getJobCatComboBox(cmbxJobT.getValue())));
jobCatCol.setOnEditCommit((CellEditEvent<Model_Time,String> t)->{
SimpleStringProperty ssp = new SimpleStringProperty(t.getNewValue());
//store selection to the object's model (unprocessed so values will show something like '6002: Kobota'
t.getRowValue().setJob(ssp);
//store row's object to the change list
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().addAll(cmbxPopulator.getLaborComboBox(t.getRowValue().getJob()));
//signaling a change has been made
isChanged = true;
});
//labor column setup works just like the job column
Laborcol.setCellValueFactory(new PropertyValueFactory<>("Labor"));
Laborcol.setCellFactory(ComboBoxTableCell.forTableColumn(cmbxPopulator.getLaborComboBox(cmbxJobCatT.getValue())));
Laborcol.setOnEditCommit((CellEditEvent<Model_Time,String> t) -> {
SimpleStringProperty ssp = new SimpleStringProperty(t.getNewValue());
t.getRowValue().setLabor(ssp);
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
t.getTableView().getItems().get(t.getTablePosition().getRow()).setLabor(ssp);
isChanged = true;
});
//time column setup.
Timecol.setCellValueFactory(new PropertyValueFactory<>("Time"));
Timecol.setCellFactory(TextFieldTableCell.<Model_Time, Float>forTableColumn(new FloatStringConverter()));
Timecol.setOnEditCommit((CellEditEvent<Model_Time,Float> t) -> {
//temp variable initialiation
float token = t.getNewValue();
//generate a temporary variable to convert the float return to a SimpleFloatProperty
SimpleFloatProperty temp = new SimpleFloatProperty(token);
//now update the row's object
t.getRowValue().setTime(temp);
//store row's object to the change list
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
isChanged = true;
});
//set tableView editable
tblviewTime.setEditable(true);
//sets tableView to allow multiline selection
TableViewSelectionModel<Model_Time> tvt = tblviewTime.getSelectionModel();
tvt.setSelectionMode(SelectionMode.MULTIPLE);
/* checks if edits have been made. If there are edits, it commits to the
database before wiping the arraylists and updating the table*/
if (isChanged == true){
/*makes sure there are no duplicate entries in the arraylist. Throws out
previous edits and takes the most recent*/
Helper_TimShArrGen.validateMatrixEntries();
//commits changes and resets the "isChanged" value.
isChanged = Helper_TimShArrGen.confirmChanges(vUsers, jobTbl, jobCatTbl, laborTbl, isChanged);
}
/*tells the kit to run the querytime Method which uses the user input data
and user data to search the timesheet tables and returns the user's time.*/
if (isChanged == false){
try {
rs = userData.queryTime(vUsers.getConn(), vUsers.getLogin_ID());
} catch (SQLException ex) {
System.out.println(ex);
}
} else {
return;
}
//sets up the observablelist for the tableview
renderTable.setTableView(tblviewTime);
ObservableList n = renderTable.generateTable(jobTbl, jobCatTbl, laborTbl, rs, vUsers.getConn());
//renders the data on the screen`
tblviewTime.setItems(n);
Helper_TimeBreakDown breakdown = new Helper_TimeBreakDown();
breakdown.setTblArr(n);
breakdown.BreakDwnTim();
lblMonTim.setText(String.valueOf(breakdown.getMon()));
lblTuesTim.setText(String.valueOf(breakdown.getTues()));
lblWedsTim.setText(String.valueOf(breakdown.getWeds()));
lblThursTim.setText(String.valueOf(breakdown.getThurs()));
lblFriTim.setText(String.valueOf(breakdown.getFri()));
lblSatTim.setText(String.valueOf(breakdown.getSat()));
lblSunTim.setText(String.valueOf(breakdown.getSun()));
lblWkTim.setText(String.valueOf(breakdown.getWeek()));
}
this is the segment from the class that handles the data that goes into the lists.
public ObservableList<String> getJobComboBox(){
//clear the jobList to clean out junk data between calls
jobList.clear();
//looks at the job table to determine if the job is active. If active, it reads the entry
for (count=0; count<= jobTbl.getTblArray().size()-1; count++){
if(jobTbl.getTblArray().get(count).isActive()){
/*here we scroll through the JobIDList and match the IDs to the jobtbl
data. When a match is hit, we grab up the number on the job and the description
this is added to another array that will become the combobox's list
*/
for(inCount = 0; inCount <= jobIDList.size()-1; inCount++){
if(jobIDList.get(inCount).getCol2ID() == jobTbl.getTblArray().get(count).getID()){
jobList.add(jobTbl.getNumById(jobIDList.get(inCount).getCol2ID())
+ ": " + jobTbl.getDescById(jobIDList.get(inCount).getCol2ID()));
}
}
}
}
/* there's probably a better dataset to use that won't allow duplicates
due to my lack of knowledge at this time, I elected to create a hashset, pass the arrayList
to the hashset to wipe out duplicates, and then pass it back to the arrayList to be used in the combobox
*/
Set<String> tmp = new HashSet();
tmp.addAll(jobList);
jobList.clear();
jobList.addAll(tmp);
jobList.add(null);
return jobList;
}
/**
*
* #param job Argument for the selected Job String
* #return returns the ObservableList of strings for the Job Category ComboBox
*/
public ObservableList<String> getJobCatComboBox(String job){
//clearing out old artifact data from the previous selection
jobCatList.clear();
//splitting the user's string selection apart (number as string, description as string)
int jID=0;
if (job != null){
if (job.contains(": ")){
String[] tmp = job.split(": ");
job = tmp[1];
}
}
// here we comb the job Table for a matching description and vacuum up the associated ID number
for(count=0; count<=jobTbl.getTblArray().size()-1; count++){
if(jobTbl.getTblArray().get(count).getDesc().equals(job)){
jID = jobTbl.getTblArray().get(count).getID();
}
}
/*using that jobID number to examine the fKey in the category table.
once we match the JobID to the fKey ID in the jobCat table, we scoop up the
the job Category code and description to create a list for the combobox
*/
for (count=0; count<= jobCTbl.getTblArray().size()-1; count++){
for(inCount = 0; inCount <= jobCatIDList.size()-1; inCount++){
if(jobCatIDList.get(inCount).getID() == jobCTbl.getTblArray().get(count).getID()){
if(jobCTbl.getTblArray().get(count).getfKeyId() == jID){
jobCatList.add(jobCTbl.getNumById(jobCatIDList.get(inCount).getID())
+ ": " + jobCTbl.getDescById(jobCatIDList.get(inCount).getID()));
}
}
}
}
//same house keeping to remove duplicates as described above
Set<String> tmp = new HashSet();
tmp.addAll(jobCatList);
jobCatList.clear();
jobCatList.addAll(tmp);
jobCatList.add(null);
return jobCatList;
}
/**
*
* #param jobCat Argument for the selected Job Category String
* #return ObservableList of strings for the Labor ComboBox
*/
public ObservableList<String> getLaborComboBox(String jobCat){
//temp arrays I needed to decode the affiliated connections
ArrayList<Integer> jCID = new ArrayList();
ArrayList<Integer> laborID = new ArrayList();
//house keeping to remove artifact data from previous selections
if(jCID != null){
jCID.clear();
}
if(laborID != null){
laborID.clear();
}
if(laborList !=null){
laborList.clear();
}
//split user's string selection for the job category (numerical code as sting, description as string)
if(jobCat != null){
if (jobCat.contains(": ")){
String[] tmp = jobCat.split(": ");
jobCat = tmp[1];
}
}
//use the description to find the affiliated job category ID
for(count=0; count<=jobCTbl.getTblArray().size()-1; count++){
if(jobCTbl.getTblArray().get(count).getDesc().equals(jobCat)){
jCID.add(jobCTbl.getTblArray().get(count).getID());
}
}
//use the job category ID to find the associated labor IDs from the associate entity table
for(count=0; count<=jCLTbl.getTblArray().size()-1; count++){
for(inCount=0; inCount<=jCID.size()-1; inCount++){
if(jCLTbl.getTblArray().get(count).getCol1ID() == jCID.get(inCount)){
laborID.add(jCLTbl.getTblArray().get(count).getCol2ID());
}
}
}
//use the labor ID to look up the needed data from the labor table.
for (count=0; count<= laborTbl.getTblArray().size()-1; count++){
for(inCount = 0; inCount <= laborID.size()-1; inCount++){
if(laborID.get(inCount) == laborTbl.getTblArray().get(count).getID()){
laborList.add(laborTbl.getNumById(laborID.get(inCount))
+ ": " + laborTbl.getDescById(laborID.get(inCount)));
}
}
}
//more housekeeping to remove duplicate entries.
Set<String> tmp = new HashSet();
tmp.addAll(laborList);
laborList.clear();
laborList.addAll(tmp);
laborList.add(null);
return laborList;
}
I know there are probably better ways to do things here. I'm still new to JAVA and coding. I work at a small company so I'm the only coder they employee. Unfortunately this limits me to what I can teach myself, so there are probably some more efficient ways to accomplish the same mission here. Anyway, if anyone could help me figure out what is going on, it would be appreciated.
The answer to this problem is actually found in the SetOnEdit portion of the jobcatCol.
upon closer inspection and a lot of debugging, I found that this line
t.getRowValue().setJob(ssp);
is actually supposed to be
t.getRowValue().setJobCat(ssp);
I also chose to forego the ComboBoxTableCell API and write my own combobox implementations for each cell. It's a very basic version found here:
public class JobComboBoxCell extends TableCell<Model_Time, String>
{
private ComboBox<String> comboBox;
private Helper_UserSpecificTimDat cmbxPopulator = new Helper_UserSpecificTimDat();
public JobComboBoxCell(Helper_UserSpecificTimDat cmbxPopulator)
{
comboBox = new ComboBox<>();
this.cmbxPopulator = cmbxPopulator;
}
#Override
public void startEdit()
{
if ( !isEmpty() )
{
super.startEdit();
comboBox.setItems( cmbxPopulator.getJobComboBox() );
comboBox.getSelectionModel().select( this.getItem() );
comboBox.focusedProperty().addListener( new ChangeListener<Boolean>()
{
#Override
public void changed( ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue )
{
if ( !newValue )
{
commitEdit( comboBox.getSelectionModel().getSelectedItem() );
}
}
} );
setText( null );
setGraphic( comboBox );
}
}
#Override
public void cancelEdit()
{
super.cancelEdit();
setText( ( String ) this.getItem() );
setGraphic( null );
}
#Override
public void updateItem( String item, boolean empty )
{
super.updateItem( item, empty );
if ( empty )
{
setText( null );
setGraphic( null );
}
else
{
if ( isEditing() )
{
setText( null );
setGraphic( comboBox );
}
else
{
setText( this.getItem() );
setGraphic( null );
}
}
}
}
This code was courtesy of Uluk Biy's response in thread:Populate combo box list dynamically for each row in javaFx table view
I adapted his code a little bit to specifically fit my needs. This solved a problem with values disappearing from the job category field and from data transferring from the job category field to the Job field.
This was one of the harder pieces of code I've had to troubleshoot. It was a combination of how the ComboBoxTableCell operates, the dynamic data of my comboboxes, and a slip in the which setter I was calling. It was about a perfect storm of flubs that the program saw no exceptions for as a result.
Thank you for the help

Manage wait cursor for task

I'm outside the UI and wish to display a wait cursor while stuff is
happening and using this basic pattern:
on UI - primaryStage.scene.cursor = Cursor.WAIT
try {
do stuff off UI...
} finally {
on UI - primaryStage.scene.cursor = Cursor.DEFAULT
}
While running I can start another process which completes quickly and the Cursor is restored before the first task completes.
I don't mind "waiting" while the first task completes, but I don't think this means doing the work on the UI thread?
Is there any built in solution for this pattern provided in javafx?
My tab contains 2 Combo Box. When I hit the 2nd Combo Box drop down, a WAIT cursor sometimes appears over the list even though the Cursor is currently DEFAULT state. If I move the mouse pointer outside/back on the list the cursor is correctly displayed as Default. Would this be a separate issue or somehow related?
VIEW
label 'From'
comboBox(items: bind(model.wcomboFromItemsProperty()), value: bind(model.wcomboFromProperty()), selectFromAction)
label 'To'
comboBox(items: bind(model.wcomboFromItemsProperty()), value: bind(model.wcomboToProperty()), selectToAction)
MODEL
#FXObservable ListElement wcomboFrom = new ListElement()
#FXObservable ListElement wcomboTo = new ListElement()
#FXObservable List wcomboFromItems = FXCollections.observableArrayList()
#FXObservable List wcomboToItems = FXCollections.observableArrayList()
final ObjectProperty<Cursor> CURSOR_DEFAULT = new SimpleObjectProperty<>(Cursor.DEFAULT)
final ObjectProperty<Cursor> CURSOR_WAIT = new SimpleObjectProperty<>(Cursor.WAIT)
CONTROLLER
//lifecycle
void onReadyStart(GriffonApplication application) {
loadWindowData()
}
// both combo boxes contain the same items
protected void loadWindowData() {
def list = [new ListElement(textValue: '')]
list.addAll dataService.getData().collect {
new ListElement(textValue: it.name, objectValue: it)
}
runInsideUIAsync {
model.wcomboFromItems.addAll(list)
model.wcomboToItems.addAll(list)
}
}
void selectFrom() {
performAction {
gcListFrom = getControlList(model.wcomboFrom.objectValue)
setTreeItems(model.wtreeGcFrom, gcListFrom, model.wcomboFrom)
setTreeItems(model.wtreeGcTo, gcListTo, model.wcomboTo)
}
}
void selectTo() {
performAction {
gcListTo = getControlList(model.wcomboTo.objectValue)
setTreeItems(model.wtreeGcTo, gcListTo, model.wcomboTo)
}
}
def performAction = {c ->
Task<Void> t = new Task() {
#Override protected Void call() {
println "Running closure " + isUIThread()
c.call()
}
}
runInsideUISync {
application.primaryStage.scene.cursorProperty().bind(Bindings.when(t.runningProperty())
.then(model.CURSOR_WAIT).otherwise(model.CURSOR_DEFAULT))
}
runOutsideUI(t)
}
OTHER
#EqualsAndHashCode(includes = 'textValue')
class ListElement implements Serializable {
String textValue = ""
Serializable objectValue // Serializable object from business model
#Override
String toString() {
textValue
}
}
The Griffon framework automatically invokes the onAction controller events outside the UI thread. GroovyFX contains some magic which adds an "onSelect" action bound to selectionModel.selectedItemProperty i.e.
class GroovyFXEnhancer {
static void enhanceClasses() {
...
ComboBox.metaClass {
cellFactory << { Closure closure -> delegate.setCellFactory(closure as Callback)}
onSelect << { Closure closure ->
delegate.selectionModel.selectedItemProperty().addListener(closure as ChangeListener);
}
...
}
}
Is there any built in solution for this pattern provided in javafx?
I would advice you to use the built in Task ;)
It has predefined methods to handle everything you need.
private Task<Void> backgroundTask = new Task() {
#Override
protected Void call() throws Exception {
// Something to do on background thread ;
return null;
}
};
It has a runningProperty(), which can bind to the cursorProperty() of the scene.
You can create two ObjectProperty<Cursor> containing Cursor.DEFAULT and CURSOR.WAIT.
final ObjectProperty<Cursor> CURSOR_DEFAULT = new SimpleObjectProperty<>(Cursor.DEFAULT);
final ObjectProperty<Cursor> CURSOR_WAIT = new SimpleObjectProperty<>(Cursor.WAIT);
Then you can bind them to the task :
scene.cursorProperty().bind(Bindings.when(backgroundTask.runningProperty())
.then(CURSOR_WAIT).otherwise(CURSOR_DEFAULT));
Would this be a separate issue or somehow related?
If your action on the ComboBox is somehow invoking the background thread, then it might be related, else it is difficult to comment.
You can also use the griffon-tasks-plugin http://griffon-plugins.github.io/griffon-tasks-plugin/
This plugin delivers and UI toolkit agnostik SwingWorker-like API for executing tasks in a background thread.

Delete JavaFX table row with delete key

Is there a way to delete selected table row using keyboard delete key?
Is there any example with this implementation?
Sure you can. You only have to register an EventHandler and listen to the specific KeyCode. Following example is for TreeTableView but should be applyable for all TableViews.
treeTableView.setOnKeyPressed( new EventHandler<KeyEvent>()
{
#Override
public void handle( final KeyEvent keyEvent )
{
final TreeItem<YourObject> selectedItem = treeTableView.getSelectionModel().getSelectedItem();
if ( selectedItem != null )
{
if ( keyEvent.getCode().equals( KeyCode.DELETE ) )
{
//Delete or whatever you like:
presenter.onEntityDeleteAction( selectedItem );
}
//... other keyevents
}
}
} );
After trying a lot I managed to intercept and handle (with my application logic) the Delete key (Del or Canc, as you prefer to call it).
Thanks to some debugging I understand that the Delete key is identified with the Unicode code: \u007F.
So, the moment I type the key, I read the character and compare it with this code.
Here is a piece of my code that has nothing to do with table views but I used it for a TextField.
The important thing is the reasoning.
#FXML
public void myKeyListener(KeyEvent keyEvent) {
//Matches and manage TAB, Enter and Delete buttons
if ((keyEvent.getCharacter().equals("\t") ||
keyEvent.getCharacter().equals("\r") ||
keyEvent.getCharacter().equals("\u007F") //<-- **THIS** is the important one! *****
)) {
//My / your application logic
keyEvent.consume(); //The documentation says: "Marks this Event as consumed. This stops its further propagation."
return;
}
//Other logic...
//Entered only to have test outputs
System.out.println("getCode: " + keyEvent.getCode());
System.out.println("getCharacter: " + keyEvent.getCharacter());
System.out.println("getText: " + keyEvent.getText());
System.out.println("isMetaDown: " + keyEvent.isMetaDown());
}
Outputs:
getCode: UNDEFINED
getCharacter: ⍰
getText:
isMetaDown: false
I hope it can be useful to someone else. 🤞
P.S. I'm using Windows 10 with italian keyboard layout. In case it's relevant.

AspectJ - Is is possible to extend an enum's value?

Say I have an enum
public enum E {A,B,C}
Is it possible to add another value, say D, by AspectJ?
After googling around, it seems that there used to be a way to hack the private static field $VALUES, then call the constructor(String, int) by reflection, but seems not working with 1.7 anymore.
Here are several links:
http://www.javaspecialists.eu/archive/Issue161.html (provided by #WimDeblauwe )
and this: http://www.jroller.com/VelkaVrana/entry/modify_enum_with_reflection
Actually, I recommend you to refactor the source code, maybe adding a collection of valid region IDs to each enumeration value. This should be straightforward enough for subsequent merging if you use Git and not some old-school SCM tool like SVN.
Maybe it would even make sense to use a dynamic data structure altogether instead of an enum if it is clear that in the future the list of commands is dynamic. But that should go into the upstream code base. I am sure the devs will accept a good patch or pull request if prepared cleanly.
Remember: Trying to avoid refactoring is usually a bad smell, a symptom of an illness, not a solution. I prefer solutions to symptomatic workarounds. Clean code rules and software craftsmanship attitude demand that.
Having said the above, now here is what you can do. It should work under JDK 7/8 and I found it on Jérôme Kehrli's blog (please be sure to add the bugfix mentioned in one of the comments below the article).
Enum extender utility:
package de.scrum_master.util;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import sun.reflect.ConstructorAccessor;
import sun.reflect.FieldAccessor;
import sun.reflect.ReflectionFactory;
public class DynamicEnumExtender {
private static ReflectionFactory reflectionFactory =
ReflectionFactory.getReflectionFactory();
private static void setFailsafeFieldValue(Field field, Object target, Object value)
throws NoSuchFieldException, IllegalAccessException
{
// let's make the field accessible
field.setAccessible(true);
// next we change the modifier in the Field instance to
// not be final anymore, thus tricking reflection into
// letting us modify the static final field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
int modifiers = modifiersField.getInt(field);
// blank out the final bit in the modifiers int
modifiers &= ~Modifier.FINAL;
modifiersField.setInt(field, modifiers);
FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false);
fa.set(target, value);
}
private static void blankField(Class<?> enumClass, String fieldName)
throws NoSuchFieldException, IllegalAccessException
{
for (Field field : Class.class.getDeclaredFields()) {
if (field.getName().contains(fieldName)) {
AccessibleObject.setAccessible(new Field[] { field }, true);
setFailsafeFieldValue(field, enumClass, null);
break;
}
}
}
private static void cleanEnumCache(Class<?> enumClass)
throws NoSuchFieldException, IllegalAccessException
{
blankField(enumClass, "enumConstantDirectory"); // Sun (Oracle?!?) JDK 1.5/6
blankField(enumClass, "enumConstants"); // IBM JDK
}
private static ConstructorAccessor getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes)
throws NoSuchMethodException
{
Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
parameterTypes[0] = String.class;
parameterTypes[1] = int.class;
System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);
return reflectionFactory.newConstructorAccessor(enumClass .getDeclaredConstructor(parameterTypes));
}
private static Object makeEnum(Class<?> enumClass, String value, int ordinal, Class<?>[] additionalTypes, Object[] additionalValues)
throws Exception
{
Object[] parms = new Object[additionalValues.length + 2];
parms[0] = value;
parms[1] = Integer.valueOf(ordinal);
System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length);
return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms));
}
/**
* Add an enum instance to the enum class given as argument
*
* #param <T> the type of the enum (implicit)
* #param enumType the class of the enum to be modified
* #param enumName the name of the new enum instance to be added to the class
*/
#SuppressWarnings("unchecked")
public static <T extends Enum<?>> void addEnum(Class<T> enumType, String enumName) {
// 0. Sanity checks
if (!Enum.class.isAssignableFrom(enumType))
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
// 1. Lookup "$VALUES" holder in enum class and get previous enum
// instances
Field valuesField = null;
Field[] fields = enumType.getDeclaredFields();
for (Field field : fields) {
if (field.getName().contains("$VALUES")) {
valuesField = field;
break;
}
}
AccessibleObject.setAccessible(new Field[] { valuesField }, true);
try {
// 2. Copy it
T[] previousValues = (T[]) valuesField.get(enumType);
List<T> values = new ArrayList<T>(Arrays.asList(previousValues));
// 3. build new enum
T newValue = (T) makeEnum(
enumType, // The target enum class
enumName, // THE NEW ENUM INSTANCE TO BE DYNAMICALLY ADDED
values.size(), new Class<?>[] {}, // could be used to pass values to the enum constuctor if needed
new Object[] {} // could be used to pass values to the enum constuctor if needed
);
// 4. add new value
values.add(newValue);
// 5. Set new values field
setFailsafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0)));
// 6. Clean enum cache
cleanEnumCache(enumType);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
}
}
Sample application & enum:
package de.scrum_master.app;
/** In honour of "The Secret of Monkey Island"... ;-) */
public enum Command {
OPEN, CLOSE, PUSH, PULL, WALK_TO, PICK_UP, TALK_TO, GIVE, USE, LOOK_AT, TURN_ON, TURN_OFF
}
package de.scrum_master.app;
public class Server {
public void executeCommand(Command command) {
System.out.println("Executing command " + command);
}
}
package de.scrum_master.app;
public class Client {
private Server server;
public Client(Server server) {
this.server = server;
}
public void issueCommand(String command) {
server.executeCommand(
Command.valueOf(
command.toUpperCase().replace(' ', '_')
)
);
}
public static void main(String[] args) {
Client client = new Client(new Server());
client.issueCommand("use");
client.issueCommand("walk to");
client.issueCommand("undress");
client.issueCommand("sleep");
}
}
Console output with original enum:
Executing command USE
Executing command WALK_TO
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant de.scrum_master.app.Command.UNDRESS
at java.lang.Enum.valueOf(Enum.java:236)
at de.scrum_master.app.Command.valueOf(Command.java:1)
at de.scrum_master.app.Client.issueCommand(Client.java:12)
at de.scrum_master.app.Client.main(Client.java:22)
Now you can either add an aspect with an advice executed after the enum class was loaded or just call this manually in your application before extended enum values are to be used for the first time. Here I am showing how it can be done in an aspect.
Enum extender aspect:
package de.scrum_master.aspect;
import de.scrum_master.app.Command;
import de.scrum_master.util.DynamicEnumExtender;
public aspect CommandExtender {
after() : staticinitialization(Command) {
System.out.println(thisJoinPoint);
DynamicEnumExtender.addEnum(Command.class, "UNDRESS");
DynamicEnumExtender.addEnum(Command.class, "SLEEP");
DynamicEnumExtender.addEnum(Command.class, "WAKE_UP");
DynamicEnumExtender.addEnum(Command.class, "DRESS");
}
}
Console output with extended enum:
staticinitialization(de.scrum_master.app.Command.<clinit>)
Executing command USE
Executing command WALK_TO
Executing command UNDRESS
Executing command SLEEP
Et voilà! ;-)

Resources