ListView validate edit and prevent commit - javafx-8

I'm using an editable ListView containing Patterns.
The user can see and edit the regexs in the list, and I'd like to validate whether the regex is syntactically correct before committing the value (and give feedback like a red border to the user).
Is there a way to do so?
patternList.setCellFactory(TextFieldListCell.forListView(new StringConverter<Pattern>() {
#Override
public String toString(Pattern pattern) {
return pattern.toString();
}
#Override
public Pattern fromString(String string) {
try {
return Pattern.compile(string);
} catch (PatternSyntaxException e) {
return null;
}
}
}));
patternList.setOnEditCommit(e -> {
if (e.getNewValue() == null) {
// TODO pattern syntax error, prevent commit and stay in edit mode
} else {
patternList.getItems().set(e.getIndex(), e.getNewValue());
}
});

I would do this by creating a TableCell implementation. E.g.:
import java.util.function.Predicate;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.css.PseudoClass;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
public class ValidatingEditingCell<S> extends TableCell<S, String> {
private final TextField textField ;
private static final PseudoClass INVALID = PseudoClass.getPseudoClass("invalid");
private BooleanProperty valid = new SimpleBooleanProperty();
public ValidatingEditingCell(Predicate<String> validator) {
this.textField = new TextField();
valid.bind(Bindings.createBooleanBinding(() -> textField.getText() != null && validator.test(textField.getText()),
textField.textProperty()));
valid.addListener((obs, wasValid, isValid) -> {
pseudoClassStateChanged(INVALID, ! isValid);
});
pseudoClassStateChanged(INVALID, ! valid.get());
textField.addEventHandler(KeyEvent.KEY_PRESSED, e -> {
if (e.getCode() == KeyCode.ENTER && valid.get()) {
commitEdit(textField.getText());
}
if (e.getCode() == KeyCode.ESCAPE) {
cancelEdit();
}
});
setGraphic(textField);
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? null : item);
textField.setText(empty ? null : item);
setContentDisplay(isEditing() ? ContentDisplay.GRAPHIC_ONLY : ContentDisplay.TEXT_ONLY);
}
#Override
public void cancelEdit() {
super.cancelEdit();
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
#Override
public void commitEdit(String newValue) {
super.commitEdit(newValue);
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
#Override
public void startEdit() {
super.startEdit();
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
textField.selectAll();
textField.requestFocus();
}
}
This takes a predicate as an argument; the predicate returns true for valid text and false for invalid text. It sets a CSS pseudoclass on the cell, so you can use CSS to style the text field (or cell itself, if needed).
Here's a simple example which validates three different columns differently:
import java.util.function.Function;
import java.util.function.Predicate;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class ValidatingTableExample extends Application {
private static <S> TableColumn<S, String> column(String title, Function<S, StringProperty> property,
Predicate<String> validator) {
TableColumn<S, String> col = new TableColumn<>(title);
col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
col.setCellFactory(tc -> new ValidatingEditingCell<>(validator));
col.setPrefWidth(150);
return col ;
}
#Override
public void start(Stage primaryStage) {
TableView<Address> table = new TableView<>();
table.setEditable(true);
table.getColumns().add(column("City", Address::cityProperty, s -> ! s.isEmpty()));
table.getColumns().add(column("State", Address::stateProperty, s -> s.length()==2));
table.getColumns().add(column("Zip", Address::zipProperty, s -> s.matches("\\d{5}")));
Button newAddress = new Button("Add");
newAddress.setOnAction(e -> {
table.getItems().add(new Address("City", "State", "Zip"));
});
Button debug = new Button("Debug");
debug.setOnAction(e ->
table.getItems().stream()
.map(address -> String.format("%s, %s %s", address.getCity(), address.getState(), address.getZip()))
.forEach(System.out::println));
HBox buttons = new HBox(5, newAddress, debug);
buttons.setAlignment(Pos.CENTER);
buttons.setPadding(new Insets(5));
BorderPane root = new BorderPane(table, null, null, buttons, null);
Scene scene = new Scene(root, 600, 600);
scene.getStylesheets().add(getClass().getResource("validating-cell.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
public static class Address {
private final StringProperty city = new SimpleStringProperty();
private final StringProperty state = new SimpleStringProperty();
private final StringProperty zip = new SimpleStringProperty();
public Address(String city, String state, String zip) {
setCity(city);
setState(state);
setZip(zip);
}
public final StringProperty cityProperty() {
return this.city;
}
public final String getCity() {
return this.cityProperty().get();
}
public final void setCity(final String city) {
this.cityProperty().set(city);
}
public final StringProperty stateProperty() {
return this.state;
}
public final String getState() {
return this.stateProperty().get();
}
public final void setState(final String state) {
this.stateProperty().set(state);
}
public final StringProperty zipProperty() {
return this.zip;
}
public final String getZip() {
return this.zipProperty().get();
}
public final void setZip(final String zip) {
this.zipProperty().set(zip);
}
}
public static void main(String[] args) {
launch(args);
}
}
and some sample CSS:
.table-cell:invalid .text-field {
-fx-focus-color: red ;
-fx-control-inner-background: #ffc0c0 ;
-fx-accent: red ;
}

I finally found a way, by overriding the commitEdit() method of TextFieldListCell:
patternList.setCellFactory(l -> new TextFieldListCell<Pattern>(new StringConverter<Pattern>() {
#Override
public String toString(Pattern pattern) {
return pattern.toString();
}
#Override
public Pattern fromString(String string) {
try {
return Pattern.compile(string);
} catch (PatternSyntaxException e) {
return null;
}
}
}) {
#Override
public void commitEdit(Pattern pattern) {
if (!isEditing()) return;
PseudoClass errorClass = PseudoClass.getPseudoClass("error");
pseudoClassStateChanged(errorClass, pattern == null);
if (pattern != null) {
super.commitEdit(pattern);
}
}
});
patternList.setOnEditCommit(e -> patternList.getItems().set(e.getIndex(), e.getNewValue()));

Related

GetActiveTasks returns 0 for StorageReference

I tried to upload a file on firebase cloud from MainActivity, i made when application is destoryed it start background services and make a file contains StorageReference.toString()
and in background service i used getReferenceFromUrl(string)
To complete the uploading and i used after it
List<UploadTask> tasks = storage.getActiveTasks();
and i used Toast.makeText(this, "tasks: " + tasks.size(), 0).show();
and it shows tasks = 0
Why? And the upload doesnt complete yet
MainActivity
import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.tasks.Task;
import com.google.android.material.appbar.AppBarLayout;
import com.google.firebase.FirebaseApp;
import com.google.firebase.storage.UploadTask;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public final int REQ_CD_IM = 101;
private Toolbar _toolbar;
private AppBarLayout _app_bar;
private CoordinatorLayout _coordinator;
private String image = "";
private UploadSaveed upload;
private String url = "";
private ImageView imageview1;
private Button button1;
private ProgressBar progressbar1;
private TextView textview1;
private AlertDialog.Builder d;
private Intent im = new Intent(Intent.ACTION_GET_CONTENT);
#Override
protected void onCreate(Bundle _savedInstanceState) {
super.onCreate(_savedInstanceState);
setContentView(R.layout.main);
initialize(_savedInstanceState);
upload = new UploadSaveed(getApplicationContext());
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, 1000);
} else {
initializeLogic();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1000) {
initializeLogic();
}
}
private void initialize(Bundle _savedInstanceState) {
_app_bar = findViewById(R.id._app_bar);
_coordinator = findViewById(R.id._coordinator);
_toolbar = findViewById(R.id._toolbar);
setSupportActionBar(_toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
_toolbar.setNavigationOnClickListener((view) -> {
onBackPressed();
});
imageview1 = findViewById(R.id.imageview1);
button1 = findViewById(R.id.button1);
progressbar1 = findViewById(R.id.progressbar1);
textview1 = findViewById(R.id.textview1);
d = new AlertDialog.Builder(this);
im.setType("*/*");
im.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
imageview1.setOnClickListener((view) -> {
startActivityForResult(im, REQ_CD_IM);
});
button1.setOnClickListener((view) -> {
upload.setUploadListener(new UploadSaveed.UploadSavedListener() {
#Override
public void onFailureListener(Exception e) {
SketchwareUtil.showMessage(getApplicationContext(), e.toString());
}
#Override
public void onProgressListener(UploadTask.TaskSnapshot task) {
double progress = (100 * task.getBytesTransferred()) / task.getTotalByteCount();
progressbar1.setProgress((int) progress);
double bytes = task.getBytesTransferred();
SketchwareUtil.showMessage(getApplicationContext(), "transferred : " + bytes);
if (upload.getUploadUrl() != null) {
url = upload.getUploadUrl();
}
}
#Override
public void onPausedListener(UploadTask.TaskSnapshot task) {
SketchwareUtil.showMessage(getApplicationContext(), "your uploading was paused");
}
#Override
public void onSuccessListener(UploadTask.TaskSnapshot task) {
Task<Uri> taskk = task.getStorage().getDownloadUrl();
while (!taskk.isSuccessful())
;
textview1.setText(taskk.getResult().toString());
SketchwareUtil.showMessage(getApplicationContext(), "finished");
}
});
upload.UploadFile(image);
});
}
private void initializeLogic() {
if (!isMyServiceRunning(UploadService.class)) {
} else {
stopService(new Intent(getApplicationContext(), UploadService.class));
stopService(new Intent(getApplicationContext(), UploadSaveed.class));
}
d.setTitle("AutoStart");
d.setMessage("You must enable autostart for application to Work in background.");
d.setPositiveButton("enable", (dialog, which) -> {
try {
final Intent intent = new Intent();
String manufacturer = Build.MANUFACTURER.toLowerCase();
if ("xiaomi".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.miui.securitycenter",
"com.miui.permcenter.autostart.AutoStartManagementActivity"));
} else if ("oppo".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.coloros.safecenter",
"com.coloros.safecenter.permission.startup.StartupAppListActivity"));
// intent.setComponent(new ComponentName("com.coloros.oppoguardelf",
// "com.coloros.powermanager.fuelgaue.PowerConsumptionActivity"));
} else if ("vivo".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.vivo.permissionmanager",
"com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
} else if ("huawei".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.huawei.systemmanager",
"com.huawei.systemmanager.optimize.process.ProtectActivity"));
} else if ("Letv".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.letv.android.letvsafe",
"com.letv.android.letvsafe.AutobootManageActivity"));
} else if ("Honor".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.huawei.systemmanager",
"com.huawei.systemmanager.optimize.process.ProtectActivity"));
} else {
return;
}
startActivity(intent);
SketchwareUtil.showMessage(getApplicationContext(),
"please enable auto start to background application");
} catch (Exception e) {
e.printStackTrace();
}
});
d.setNegativeButton("I already enabled it", (dialog, which) -> {
});
d.create().show();
}
#Override
protected void onActivityResult(int _requestCode, int _resultCode, Intent _data) {
super.onActivityResult(_requestCode, _resultCode, _data);
switch (_requestCode) {
case REQ_CD_IM:
if (_resultCode == Activity.RESULT_OK) {
ArrayList<String> _filePath = new ArrayList<>();
if (_data != null) {
if (_data.getClipData() != null) {
for (int _index = 0; _index < _data.getClipData().getItemCount(); _index++) {
ClipData.Item _item = _data.getClipData().getItemAt(_index);
_filePath.add(FileUtil.convertUriToFilePath(getApplicationContext(), _item.getUri()));
}
} else {
_filePath.add(FileUtil.convertUriToFilePath(getApplicationContext(), _data.getData()));
}
}
image = _filePath.get((int) (0));
} else {
}
break;
default:
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
File fi = new File(Environment.getExternalStorageDirectory(), "saved");
if (!fi.exists()) {
fi.mkdirs();
}
File gpxfile = new File(fi, "saved.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append(url);
writer.flush();
writer.close();
} catch (IOException ee) {
ee.printStackTrace();
}
upload.PauseUploading();
startService(new Intent(this, UploadService.class));
startService(new Intent(getApplicationContext(), UploadSaveed.class));
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
UploadService
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import com.google.android.gms.tasks.Task;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class UploadService extends Service {
public static final String TAG = "UploadService";
private UploadSaveed upload;
#Nullable
#Override
public IBinder onBind(Intent i) {
return null;
}
#Override
public int onStartCommand(Intent i, int flags, int startId) {
upload = new UploadSaveed(getApplicationContext());
upload.setUploadListener(new UploadSaveed.UploadSavedListener() {
#Override
public void onFailureListener(Exception e) {
simpleNotifaction(1, "Upload Faild", "Upload Faild !");
try {
File fi = new File(Environment.getExternalStorageDirectory(), "saved");
if (!fi.exists()) {
fi.mkdirs();
}
File gpxfile = new File(fi, "errors.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append(e.toString());
writer.flush();
writer.close();
} catch (IOException ee) {
ee.printStackTrace();
}
}
#Override
public void onProgressListener(UploadTask.TaskSnapshot task) {
double progress = (100 * task.getBytesTransferred()) / task.getTotalByteCount();
notiProgress(1, "Uploading", "Your file is Uploading..", progress);
}
#Override
public void onPausedListener(UploadTask.TaskSnapshot task) {
SketchwareUtil.showMessage(getApplicationContext(), "your uploading is paused");
}
#Override
public void onSuccessListener(UploadTask.TaskSnapshot task) {
Task<Uri> taskk = task.getStorage().getDownloadUrl();
while (!taskk.isSuccessful())
;
simpleNotifaction(1, "Uploaded", "Url: " + taskk.getResult().toString());
stopSelf();
}
});
upload.UploadFormUrl(upload.getUploadUrl2());
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent i) {
startService(new Intent(this, UploadService.class));
super.onTaskRemoved(i);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
}
private void notiProgress(final double _id, final String _title, final String _text, final double _progress) {
final Context context = getApplicationContext();
android.app.NotificationManager notificationManager = (android.app.NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
androidx.core.app.NotificationCompat.Builder builder;
int notificationId = (int) _id;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = android.app.NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
android.app.NotificationChannel mChannel = new android.app.NotificationChannel(channelId, channelName,
importance);
notificationManager.createNotificationChannel(mChannel);
}
androidx.core.app.NotificationCompat.Builder mBuilder = new androidx.core.app.NotificationCompat.Builder(
context, channelId).setSmallIcon(android.R.drawable.stat_sys_upload).setTicker("")
.setContentTitle(_title).setContentText(_text).setProgress((int) 100, (int) _progress, false);
notificationManager.notify(notificationId, mBuilder.build());
}
private void simpleNotifaction(int id2, String title, String description) {
androidx.core.app.NotificationCompat.Builder builder = new androidx.core.app.NotificationCompat.Builder(this,
"channel-01")
.setSmallIcon(android.R.drawable.stat_sys_upload_done)
.setSound(android.media.RingtoneManager
.getDefaultUri(android.media.RingtoneManager.TYPE_NOTIFICATION))
.setContentTitle(title).setContentText(description)
.setPriority(androidx.core.app.NotificationCompat.PRIORITY_MAX).setAutoCancel(true);
androidx.core.app.NotificationManagerCompat notificationManager = androidx.core.app.NotificationManagerCompat
.from(this);
notificationManager.notify(id2, builder.build());
}
}
UploadSaveed
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
import java.util.List;
import java.util.Scanner;
public class UploadSaveed extends Service {
public static final String TAG = "UploadSaveed";
private FirebaseApp app;
private StorageReference storagee, path;
private UploadTask path2;
private List<UploadTask> tasks;
private String urll;
#Nullable
#Override
public IBinder onBind(Intent i) {
return null;
}
#Override
public int onStartCommand(Intent i, int flags, int startId) {
return START_STICKY;
}
public interface UploadSavedListener {
void onProgressListener(#NonNull UploadTask.TaskSnapshot task);
void onFailureListener(#NonNull Exception e);
void onSuccessListener(#NonNull UploadTask.TaskSnapshot task);
void onPausedListener(#NonNull UploadTask.TaskSnapshot task);
}
private UploadSavedListener listener;
public void setUploadListener(UploadSavedListener listener) {
this.listener = listener;
}
public UploadSaveed() {
}
public UploadSaveed(Context c) {
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:982483603219:android:ce7ef5f660652cdca054e6")
.setApiKey("AIzaSyAhffAnCI7dG0d3NucUAjPM6oWaX6mVSHk")
.setDatabaseUrl("trav-chat-2-default-rtdb.firebaseio.com").setStorageBucket("trav-chat-2.appspot.com")
.build();
try {
FirebaseApp.initializeApp(c, options, "firebasedb");
app = FirebaseApp.getInstance("firebasedb");
} catch (Exception e) {
e.printStackTrace();
FirebaseApp.initializeApp(c, options);
app = FirebaseApp.getInstance("firebasedb");
}
try {
File fi = new File(Environment.getExternalStorageDirectory(), "saved");
if (!fi.exists()) {
fi.mkdirs();
}
File gpxfile = new File(fi, "ssaved.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append(app.toString());
writer.flush();
writer.close();
} catch (IOException ee) {
ee.printStackTrace();
}
}
public void UploadFile(String file) {
Uri file2 = Uri.parse(file);
Uri file3 = Uri.fromFile(new File(file));
storagee = FirebaseStorage.getInstance(app).getReference();
path = storagee.child("test image").child(file2.getLastPathSegment());
path2 = path.putFile(file3);
if (listener != null) {
path2.addOnFailureListener((e) -> {
listener.onFailureListener(e);
}).addOnPausedListener((task) -> {
listener.onPausedListener(task);
}).addOnProgressListener((task) -> {
listener.onProgressListener(task);
}).addOnSuccessListener((task) -> {
listener.onSuccessListener(task);
});
} else if (listener == null) {
throw new IllegalArgumentException("listener cannot be null");
}
}
/*
public void UploadFormUrl(String url) {
storagee = FirebaseStorage.getInstance(app).getReferenceFromUrl(url);
tasks = storagee.getActiveUploadTasks();
if (tasks.size() > 0) {
if (listener != null) {
path2 = tasks.get(0);
ResumeUploading();
SketchwareUtil.showMessage(this, "lol");
path2.addOnFailureListener((e) -> {
listener.onFailureListener(e);
}).addOnPausedListener((task) -> {
listener.onPausedListener(task);
}).addOnProgressListener((task) -> {
listener.onProgressListener(task);
}).addOnSuccessListener((task) -> {
listener.onSuccessListener(task);
});
} else {
throw new IllegalArgumentException("listener cannot be null");
}
} else {
throw new IllegalArgumentException("tasks cannot be equal 0 or less");
}
}
*/
public String getUploadUrl() {
if (path != null) {
return path.toString();
} else if (storagee != null) {
return storagee.toString();
} else {
throw new IllegalArgumentException("Storage Reference is null");
}
}
public void CancelUploading() {
path2.cancel();
}
public void PauseUploading() {
path2.pause();
}
public void ResumeUploading() {
path2.resume();
}
public String getUploadUrl2() {
urll = FileUtil.readFile(Environment.getExternalStorageDirectory().toString() + "/saved/saved.txt");
return urll;
}
#Override
public void onTaskRemoved(Intent i) {
startService(new Intent(this, UploadSaveed.class));
super.onTaskRemoved(i);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
}
}
Try to use intent
Try this code:
val intent = Intent(this, Main2Activity::class.java)
startActivity(intent)

CheckBoxTableCell select entire column

I can not get the value of the checkbox, whether it is selected or not.
I can not select or deselect the entire column of CheckBoxTableCell
//CLASS MODELO
public class Cidade{
private Integer codigo;
private String descricao;
public AAA(Integer codigo, String descricao) {
super();
this.codigo = codigo;
this.descricao = descricao;
}
public Integer getCodigo() {
return codigo;
}
public String getDescricao() {
return descricao;
}
}
//CREATION OF COLUMNS OF TABLEVIEW
TableView tbView = new TableView();
tbView.setEditable(true);
TableColumn colCheck = new TableColumn();
colCheck.setCellFactory(CheckBoxTableCell.forTableColumn(colCheck));
CheckBox cbk = new CheckBox();
cbk.selectedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
// TODO Auto-generated method stub
if (!tbView.getItems().isEmpty())
if (newValue)
for (int i = 0; i < tbView.getItems().size(); i++) {
((CheckBox) ((TableColumn) tbView.getColumns().get(0)).getGraphic()).selectedProperty().get();
}
}
});
colCheck.setGraphic(cbk);
tbView.getColumns().add(colCheck);
TableColumn colCode = new TableColumn("Codido");
colCode.setCellValueFactory(new PropertyValueFactory("codigo"));
TableColumn colDescricao = new TableColumn("Descricao");
colCode.setCellValueFactory(new PropertyValueFactory("descricao"));
tbView.getColumns().addAll(colCode,colDescricao);
The CheckBoxTableCell expects a selectedStateCallback, which is a function mapping the row index to an ObservableValue<Boolean> that determines if the check box should be checked. If the supplied observable value is also a WritableValue<Boolean>, then when the user checks or unchecks the check box, the value will be updated.
The simplest case for this is when the model for the table has a boolean property which is represented by the check box. However, this doesn't have to be the case. For example, you could create a map from your table items to a boolean property, and use the properties in that map for the selected state of the check boxes:
Map<T, BooleanProperty> checkedRows = new HashMap<>();
checkColumn.setCellFactory(CheckBoxTableCell.forTableColumn(i ->
checkedRows.computeIfAbsent(table.getItems().get(i), p -> new SimpleBooleanProperty())));
Here you would replace T with the actual type of your table.
You probably want to ensure the map doesn't hold references to items that are no longer part of your table:
// clear obsolete table items from map:
table.getItems().addListener((Change<? extends T> c) -> {
if (c.wasRemoved()) {
c.getRemoved().forEach(checkedRows::remove);
}
});
Now you would just use the map to check for which items are checked:
T item = ... ;
boolean itemIsChecked = checkedRows.getOrDefault(item, new SimpleBooleanProperty(false)).get() ;
or get all the checked items with
List<T> checkedItems = checkedRows.entrySet().stream()
.filter(e -> e.getValue().get())
.map(Entry::getKey)
.collect(Collectors.toList());
You can select everything with
table.getItems().forEach(item ->
checkedRows.computeIfAbsent(item , item -> new SimpleBooleanProperty()).set(true));
and similarly deselect by setting to false.
Here is a complete SSCCE using the usual address book example:
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener.Change;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class TableViewWithCheckBoxColumn extends Application {
#Override
public void start(Stage primaryStage) {
TableView<Person> table = new TableView<>();
table.setEditable(true);
TableColumn<Person, Void> checkColumn = new TableColumn<>();
table.getColumns().add(checkColumn);
Map<Person, BooleanProperty> checkedRows = new HashMap<>();
// clear obsolete table items from map:
table.getItems().addListener((Change<? extends Person> c) -> {
if (c.wasRemoved()) {
c.getRemoved().forEach(checkedRows::remove);
}
});
checkColumn.setCellFactory(CheckBoxTableCell.forTableColumn(i ->
checkedRows.computeIfAbsent(table.getItems().get(i), p -> new SimpleBooleanProperty())));
CheckBox checkAll = new CheckBox();
checkAll.setOnAction(e -> {
if (checkAll.isSelected()) {
table.getItems().forEach(p ->
checkedRows.computeIfAbsent(p, person -> new SimpleBooleanProperty()).set(true));
} else{
checkedRows.values().stream().forEach(checked -> checked.set(false));
}
});
checkColumn.setGraphic(checkAll);
checkColumn.setEditable(true);
table.getColumns().add(column("First Name", Person::firstNameProperty));
table.getColumns().add(column("Last Name", Person::lastNameProperty));
table.getColumns().add(column("Email", Person::emailProperty));
table.getItems().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")
);
Button verify = new Button("Verify");
verify.setOnAction(evt -> {
checkedRows.entrySet().stream().filter(e -> e.getValue().get()).map(Entry::getKey)
.map(Person::getFirstName).forEach(System.out::println);
});
BorderPane root = new BorderPane(table);
BorderPane.setAlignment(verify, Pos.CENTER);
BorderPane.setMargin(verify, new Insets(5));
root.setBottom(verify);
primaryStage.setScene(new Scene(root, 600, 600));
primaryStage.show();
}
private static <S,T> TableColumn<S,T> column(String title, Function<S, ObservableValue<T>> property) {
TableColumn<S,T> col = new TableColumn<>(title);
col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
return col ;
}
public static void main(String[] args) {
launch(args);
}
}
with the usual Person model class:
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Person {
private final StringProperty firstName = new SimpleStringProperty();
private final StringProperty lastName = new SimpleStringProperty();
private final StringProperty email = new SimpleStringProperty();
public Person(String firstName, String lastName, String email) {
setFirstName(firstName);
setLastName(lastName);
setEmail(email);
}
public final StringProperty firstNameProperty() {
return this.firstName;
}
public final String getFirstName() {
return this.firstNameProperty().get();
}
public final void setFirstName(final String firstName) {
this.firstNameProperty().set(firstName);
}
public final StringProperty lastNameProperty() {
return this.lastName;
}
public final String getLastName() {
return this.lastNameProperty().get();
}
public final void setLastName(final String lastName) {
this.lastNameProperty().set(lastName);
}
public final StringProperty emailProperty() {
return this.email;
}
public final String getEmail() {
return this.emailProperty().get();
}
public final void setEmail(final String email) {
this.emailProperty().set(email);
}
}

GWT CellTree inside a DataGrid does not react to mouse-clicks

I have put a GWT-CellTree in a DataGrid. It works except for one thing: When clicking on the tree-expand-icon, nothing happens. I have tried to minimize the
code needed to reproduce the problem...
How can this be fixed ?
best regards, Magnus
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.SimpleLayoutPanel;
public class HelloWorld implements EntryPoint {
public void onModuleLoad() {
DataGrid grid= (DataGrid) new NodesGrid().getTable();
grid.setWidth("100%");
SimpleLayoutPanel slp = new SimpleLayoutPanel();
slp.add(grid);
RootLayoutPanel.get().add(slp);
}
}
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.dom.client.Style;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
import com.google.gwt.text.shared.SafeHtmlRenderer;
import com.google.gwt.user.cellview.client.*;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.view.client.ListDataProvider;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
public class NodesGrid {
private AbstractCellTable<Node> table = new DataGrid<>();
private Column nameColumn;
private Column<Node, String> showBlocksColumn;
private final Set<Integer> showBlocks = new HashSet<>();
public Column getNameColumn() {
return nameColumn;
}
public AbstractCellTable<Node> getTable() {
return table;
}
public NodesGrid() {
table.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
table.setWidth("100%");
CustomCellTableBuilder c = new CustomCellTableBuilder(this, table);
table.setTableBuilder(c);
Node nodes = new Node();
nodes.setName("hello");
nodes.setId(123);
Node n2 = new Node();
n2.setName("testing");
nodes.getBlocks().add(n2);
ListDataProvider<Node> dataProvider = new ListDataProvider<>();
dataProvider.addDataDisplay(table);
List<Node> list = dataProvider.getList();
list.add(nodes);
addShowBlocks();
nameColumn = getSorter(list, "Name", Comparator.comparing(Node::getName), Node::getName);
}
private Column getSorter(List<Node> list,
String name,
Comparator<Node> cmp,
Function<Node, String> supplier) {
TextColumn<Node> column = new TextColumn<Node>() {
#Override
public String getValue(Node object) {
return supplier.apply(object);
}
};
table.addColumn(column, name);
column.setSortable(true);
ColumnSortEvent.ListHandler<Node> columnSortHandler = new ColumnSortEvent.ListHandler<>(list);
columnSortHandler.setComparator(column, cmp);
table.addColumnSortHandler(columnSortHandler);
table.getColumnSortList().push(column);
return column;
}
public Column<Node, String> getShowBlocksColumn() {
return showBlocksColumn;
}
public Set<Integer> getShowBlocks() {
return showBlocks;
}
void addShowBlocks() {
SafeHtmlRenderer<String> anchorRenderer = new AbstractSafeHtmlRenderer<String>() {
#Override
public SafeHtml render(String object) {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("(<a href=\"javascript:;\">").appendEscaped(object)
.appendHtmlConstant("</a>)");
return sb.toSafeHtml();
}
};
showBlocksColumn = new Column<Node, String>(new ClickableTextCell(anchorRenderer)) {
#Override
public String getValue(Node node) {
if (showBlocks.contains(node.getId())) {
return "hide blocks";
} else {
return "show blocks";
}
}
};
showBlocksColumn.setFieldUpdater(new FieldUpdater<Node, String>() {
#Override
public void update(int index, Node node, String value) {
if (showBlocks.contains(node.getId())) {
showBlocks.remove(node.getId());
} else {
showBlocks.add(node.getId());
}
table.redrawRow(index);
}
});
table.addColumn(showBlocksColumn);
table.setColumnWidth(0, 10, Style.Unit.EM);
}
}
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.CellTree;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.TreeNode;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.view.client.TreeViewModel;
import java.util.ArrayList;
import java.util.List;
public class NodesTree {
private CellTree tree;
public NodesTree(Node node) {
TreeViewModel model = new CustomTreeModel(node);
tree = new CellTree(model, null);
tree.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
TreeNode rootNode = tree.getRootTreeNode();
openAll(rootNode);
}
private static class TopLevel {
private final String name;
private List<Node> blocks = new ArrayList<>();
public TopLevel(String name) {
this.name = name;
}
public TopLevel(String name, List<Node> blocks) {
this.name = name;
this.blocks = blocks;
}
public String getName() {
return name;
}
public List<Node> getBlocks() {
return blocks;
}
}
private static class CustomTreeModel implements TreeViewModel {
private final List<TopLevel> topLevels;
private final SingleSelectionModel<String> selectionModel
= new SingleSelectionModel<>();
public CustomTreeModel(Node node) {
topLevels = new ArrayList<>();
{
TopLevel blocksNode = new TopLevel("Blocks", new ArrayList(node.getBlocks()));
topLevels.add(blocksNode);
}
{
TopLevel outgoing = new TopLevel("Outgoing");
topLevels.add(outgoing);
}
{
TopLevel incoming = new TopLevel("Incoming");
topLevels.add(incoming);
}
}
public <T> NodeInfo<?> getNodeInfo(T value) {
if (value == null) {
// LEVEL 0.
ListDataProvider<TopLevel> dataProvider
= new ListDataProvider<>(
topLevels);
Cell<TopLevel> cell = new AbstractCell<TopLevel>() {
#Override
public void render(Context context, TopLevel value, SafeHtmlBuilder sb) {
sb.appendHtmlConstant(" ");
sb.appendEscaped(value.getName());
}
};
return new DefaultNodeInfo<>(dataProvider, cell);
} else if (value instanceof TopLevel) {
// LEVEL 1.
ListDataProvider<Node> dataProvider = new ListDataProvider<>(((TopLevel) value).getBlocks());
Cell<Node> cell = new AbstractCell<Node>() {
#Override
public void render(Context context, Node value, SafeHtmlBuilder sb) {
if (value != null) {
sb.appendHtmlConstant(" ");
sb.appendEscaped("(" + value.getName() + ")");
}
}
};
return new DefaultNodeInfo<>(dataProvider, cell);
} else if (value instanceof Node) {
// LEVEL 2 - LEAF.
String params = "test";
ArrayList<String> str = new ArrayList<>();
str.add(params);
ListDataProvider<String> dataProvider = new ListDataProvider<>(str);
return new DefaultNodeInfo<>(dataProvider, new TextCell(), selectionModel, null);
}
return null;
}
public boolean isLeaf(Object value) {
if (value instanceof String) {
return true;
}
return false;
}
}
private void openAll(TreeNode rootNode) {
if (rootNode == null) return;
for (int i = 0; i < rootNode.getChildCount(); i++) {
TreeNode node = rootNode.setChildOpen(i, true);
openAll(node);
}
}
public Widget getWidget() {
return tree;
}
}
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.dom.builder.shared.DivBuilder;
import com.google.gwt.dom.builder.shared.TableCellBuilder;
import com.google.gwt.dom.builder.shared.TableRowBuilder;
import com.google.gwt.dom.client.Style;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.cellview.client.AbstractCellTable;
import com.google.gwt.user.cellview.client.AbstractCellTableBuilder;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.view.client.SelectionModel;
public class CustomCellTableBuilder extends AbstractCellTableBuilder<Node> {
NodesGrid nodesGrid;
private final String rowStyle;
private final String selectedRowStyle;
private final String cellStyle;
private final String selectedCellStyle;
/**
* Construct a new table builder.
*
* #param cellTable the table this builder will build rows for
*/
public CustomCellTableBuilder(NodesGrid nodesGrid, AbstractCellTable<Node> cellTable) {
super(cellTable);
this.nodesGrid = nodesGrid;
AbstractCellTable.Style style = cellTable.getResources().style();
rowStyle = style.evenRow();
selectedRowStyle = " " + style.selectedRow();
cellStyle = style.cell() + " " + style.evenRowCell();
selectedCellStyle = " " + style.selectedRowCell();
}
#Override
protected void buildRowImpl(Node rowValue, int absRowIndex) {
// Calculate the row styles.
SelectionModel<? super Node> selectionModel = cellTable.getSelectionModel();
boolean isSelected =
(selectionModel == null || rowValue == null) ? false : selectionModel
.isSelected(rowValue);
StringBuilder trClasses = new StringBuilder(rowStyle);
if (isSelected) {
trClasses.append(selectedRowStyle);
}
String cellStyles = cellStyle;
if (isSelected) {
cellStyles += selectedCellStyle;
}
TableRowBuilder row = startRow();
row.className(trClasses.toString());
buildRow(row, rowValue, cellStyles, nodesGrid.getShowBlocksColumn());
buildRow(row, rowValue, cellStyles, nodesGrid.getNameColumn());
row.endTR();
if (nodesGrid.getShowBlocks().contains(rowValue.getId())) {
buildBlockRow(rowValue, cellStyles);
}
}
void buildRow(TableRowBuilder row, Node rowValue, String cellStyles, Column column) {
TableCellBuilder td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
renderCell(td, createContext(0), column, rowValue);
td.endTD();
}
private void buildBlockRow(Node rowValue, String cellStyles) {
TableRowBuilder row = startRow();
buildCell(rowValue, cellStyles, row);
row.endTR();
}
private void buildCell(Node rowValue, String cellStyles, TableRowBuilder row) {
NodesTree hw = new NodesTree(rowValue);
TableCellBuilder td = row.startTD().colSpan(5);
td.className(cellStyles);
DivBuilder div = td.startDiv();
String t = hw.getWidget().getElement().getInnerHTML();
div.html(SafeHtmlUtils.fromTrustedString(t));
div.end();
td.endTD();
}
}
package com.raybased.gwt.configtool.client.grid;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Node implements Serializable {
String name;
List<Node> blocks = new ArrayList<>();
String params;
int id;
public Node() {
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
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;
}
public List<Node> getBlocks() {
return blocks;
}
}

Javafx Combobox list index set to -1 when executing combobox.get(someobject)

I have a combo box that is populated with the following ObservableList:
final ObservableList<SimplePerson> persons = FXCollections.observableArrayList(
new SimplePerson("Jacob", 1),
new SimplePerson("Isabella", 2),
new SimplePerson("Ethan", 3),
new SimplePerson("Emma", 4),
new SimplePerson("Michael", 5)
);
The combobox's selected index will be set to -1, the combobox's textbox will be populated with "Michael", and the "Michael" item in the drop down list will not be selected when I run
setValue(new SimplePerson("Michael",5))
Here is some example code (SSCCE)
import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.property.IntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import javafx.util.Callback;
import javafx.scene.control.ListView;
import javafx.scene.control.ListCell;
public class ComboBoxDemo extends Application {
public class SimplePerson {
private StringProperty name;
private IntegerProperty id;
private String somethingElse;
public SimplePerson(String name, Integer id) {
setName(name);
setId(id);
}
public final void setName(String value) {
nameProperty().set(value);
}
public final void setId(Integer id) {
idProperty().set(id);
}
public String getName() {
return nameProperty().get();
}
public int getId() {
return idProperty().get();
}
public StringProperty nameProperty() {
if (name == null) {
name = new SimpleStringProperty(this, "name");
}
return name;
}
public IntegerProperty idProperty() {
if (id == null) {
id = new SimpleIntegerProperty(this, "id");
}
return id;
}
#Override
public String toString() {
return name.get();
}
}
final ObservableList<SimplePerson> persons = FXCollections.observableArrayList(
new SimplePerson("Jacob", 1),
new SimplePerson("Isabella", 2),
new SimplePerson("Ethan", 3),
new SimplePerson("Emma", 4),
new SimplePerson("Michael", 5)
);
#Override
public void start(Stage stage) throws Exception {
final ComboBox<SimplePerson> cb = new ComboBox<>();
final ComboBox<String> cb2 = new ComboBox<>();
cb.setItems(persons);
cb.setEditable(true);
cb.setConverter(new StringConverter<SimplePerson>() {
#Override
public String toString(SimplePerson p) {
if (p != null) {
System.out.println("Looking up toString " + p.getName());
return p.getName();
} else {
System.out.println("Looking up toString null");
return "";
}
}
#Override
public SimplePerson fromString(String name) {
if (cb.getValue() != null) {
((SimplePerson) cb.getValue()).setName(name);
cb.show();
System.out.println("Here I am" + ((SimplePerson) cb.getValue()).getName());
return (SimplePerson) cb.getValue();
}
System.out.println("Returning null");
return null;
}
});
stage.setScene(new Scene(cb));
stage.show();
cb.setCellFactory(new Callback<ListView<SimplePerson>, ListCell<SimplePerson>>() {
#Override
public ListCell<SimplePerson> call(ListView<SimplePerson> l) {
return new ListCell<SimplePerson>() {
#Override
protected void updateItem(SimplePerson item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
System.out.println("I'm null");
} else {
System.out.println("Go get them " + item.getName());
setText(item.getName());
}
}
};
}
});
cb.setValue(new SimplePerson("Michael", 5));
System.out.println(cb.getSelectionModel().getSelectedIndex());
System.out.println(cb.getValue().getName());
}
public static void main(String[] args) {
launch(args);
}
}
The drop down list will select the right item when the ObservableList contains Strings
ObservableList<String>
You are passing a new Object to setValue() into the ComboBox. The Michael that is displayed when the ComboBox pops up is not same as the Michael in the dropdown.
If you pass cb.setValue(new SimplePerson("xyz", 5)); then the ComboBox will show the initially selected item as xyz, where xyz is not in the List of Person.
To set the exact object, you need to fetch them from their original reference, which in your case is the ObservableList<SimplePerson> persons. To fetch Michael, we use its index :
cb.setValue(persons.get(4));

JavaFX TableView with Custom Cell Datepicker "OnEditCommit" is not invoked

Hi everyone !!
I'm working with JavaFX and the JDK 8.
I got a TableView filled by a database with the use of a JavaFX POJO Class "Inputs". I've implemented TexField cells, ComboBoxes cells and Checkbox cells succesfully.
But I am not able to make it working with DatePicker Control: the event on the "setOnEditComit" is never invoked...
Hre is my code:
Declarations for TableColumn:
#FXML
private TableColumn<Inputs,LocalDate> colDate = new TableColumn<Inputs,LocalDate>();
[...]
colDate.setCellValueFactory(
new PropertyValueFactory<Inputs,LocalDate>("localdate"));
Callback<TableColumn<Inputs, LocalDate>, TableCell<Inputs, LocalDate>> dateCellFactory =
new Callback<TableColumn<Inputs, LocalDate>, TableCell<Inputs, LocalDate>>() {
public TableCell call(TableColumn p) {
return new EditingDatePickerCell();
}
};
[...]
colDate.setOnEditCommit(
new EventHandler<CellEditEvent<Inputs, LocalDate>>() {
#Override
public void handle(CellEditEvent<Inputs, LocalDate> event) {
System.out.println("EVENT!!!!");
((Inputs) event.getTableView().getItems().get(
event.getTablePosition().getRow())
).setDatePicker(event.getNewValue());
}
}
);
With these JavaFX POJO Objects declarations:
public ObjectProperty<LocalDate> localdate;
[...]
this.localdate = new SimpleObjectProperty<LocalDate>(localdate);
[...]
public LocalDate getDatePicker() {
return localdate.getValue();
}
[...]
public void setDatePicker(LocalDate value) {
System.out.println("EVENT!!!!");
localdate.setValue(value);
}
[...]
public ObjectProperty<LocalDate> localdateProperty() {
return localdate;
}
EditingDatePickerCell class:
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import com.desktop.newapp.utils.Inputs;
public class EditingDatePickerCell <Inputs, LocalDate> extends TableCell<Inputs, LocalDate> {
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createDatePicker();
setText(null);
setGraphic(datePicker);
datePicker.requestFocus();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
datePicker.setValue((java.time.LocalDate) getItem());
setGraphic(null);
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
private DatePicker datePicker;
public EditingDatePickerCell() {
if (datePicker == null) {
createDatePicker();
}
setGraphic(datePicker);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
Platform.runLater(new Runnable() {
#Override
public void run() {
datePicker.requestFocus();
}
});
}
#Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (datePicker != null && item != null) {
datePicker.setValue((java.time.LocalDate) getLocalDate());
commitEdit(getLocalDate());
}
setGraphic(datePicker);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
}
private void createDatePicker() {
datePicker = new DatePicker();
datePicker.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
setGraphic(datePicker);
datePicker.addEventFilter(KeyEvent.KEY_PRESSED,new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(getLocalDate());
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
} else if (t.getCode() == KeyCode.TAB) {
commitEdit(getLocalDate());;
}
}
});
setAlignment(Pos.CENTER);
}
private LocalDate getLocalDate() {
return getItem();
///return datePicker.getValue() != null ? datePicker.getValue() : getItem();
}
}
I've been Googling a lot and I didn't find any correct implementation of the Java8 DatePicker Editing capabilities in a JavaFX TableView. Any help would be very appreciate !!
Without Stackoverflow I'll never could done the quarter of the whole job so long life to Stackoverflow !!
Regards.
You need to put the table in editing mode (for the current row) when the user interacts with the picker. That can be achieved with an onShowingHandler like this (example is also with a color picker):
this.colorPicker.setOnShowing(event -> {
final TableView<T> tableView = getTableView();
tableView.getSelectionModel().select(getTableRow().getIndex());
tableView.edit(tableView.getSelectionModel().getSelectedIndex(), column);
});
then watch the valueProperty of the picker like this:
this.colorPicker.valueProperty().addListener((observable, oldValue, newValue) -> {
if(isEditing()) {
commitEdit(newValue);
}
});
For more explanation have a look at my blog post: Custom editor components in JavaFX TableCells.
Full Class:
public class ColorTableCell<T> extends TableCell<T, Color> {
private final ColorPicker colorPicker;
public ColorTableCell(TableColumn<T, Color> column) {
this.colorPicker = new ColorPicker();
this.colorPicker.editableProperty().bind(column.editableProperty());
this.colorPicker.disableProperty().bind(column.editableProperty().not());
this.colorPicker.setOnShowing(event -> {
final TableView<T> tableView = getTableView();
tableView.getSelectionModel().select(getTableRow().getIndex());
tableView.edit(tableView.getSelectionModel().getSelectedIndex(), column);
});
this.colorPicker.valueProperty().addListener((observable, oldValue, newValue) -> {
if(isEditing()) {
commitEdit(newValue);
}
});
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
#Override
protected void updateItem(Color item, boolean empty) {
super.updateItem(item, empty);
setText(null);
if(empty) {
setGraphic(null);
} else {
this.colorPicker.setValue(item);
this.setGraphic(this.colorPicker);
}
}
}
I was having the same issues but i ended up solving it with this post. JavaFX8 – Render a DatePicker Cell in a TableView.
The outcome is illustrated in the image below.
Your Model object is a bit strange. The setDatePicker and getDatePicker methods should be called setLocaldate and getLocaldate, to be consistent with the localdateProperty() method and (possibly importantly) the parameter passed to the PropertyValueFactory.
I don't think that would cause the problem you observe, though, and I can't see what else is wrong.
This example works for me.
Have a look and see if you can see what I did that's different...
here is a datapicker cell edit when pressing tab key and go to the next cell
datePicker.setOnKeyPressed /EventHandler doesnot work with tab
datePicker.EventFilter get called twice
to work arround this you need to add a listner to tableview cell and get date text as string and cast it to localdate
addEventFilter to TableCell deduction object is a sample
=> addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler() {...}
public class DatePickerCell extends TableCell<Deduction, LocalDate> {
private DatePicker datePicker;
private TableColumn column;
// private TableCell cell;
public DatePickerCell(TableColumn column) { //
super();
this.column = column;
this.datePicker = new DatePicker(getDate());
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createDatePicker();
setText(null);
setGraphic(datePicker);
Platform.runLater(new Runnable() {
#Override
public void run() {
datePicker.requestFocus();
}
});
//Platform.runLater(datePicker::requestFocus);
}
}
#Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
// SimpleDateFormat smp = new SimpleDateFormat("dd/MM/yyyy");
/* if (null == this.datePicker) {
System.out.println("datePicker is NULL");
}*/ //TO be reviewed
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (datePicker != null) {
datePicker.setValue(getItem());
}
setText(null);
setGraphic(datePicker);
} else {
setText(getItem().toString());
setGraphic(null);
}
}
}
private LocalDate getDate() {
return getItem() == null ? LocalDate.now() : getItem();
}
private void createDatePicker() {
this.datePicker = new DatePicker(getDate());
datePicker.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
this.datePicker.editableProperty().bind(column.editableProperty());
this.datePicker.disableProperty().bind(column.editableProperty().not());
this.datePicker.setOnShowing(event -> {
final TableView tableView = getTableView();
tableView.getSelectionModel().select(getTableRow().getIndex());
tableView.edit(tableView.getSelectionModel().getSelectedIndex(), column);
});
datePicker.setOnAction((e) -> {
commitEdit(datePicker.getValue());
TableColumn nextColumn = getNextColumn(true);
if (nextColumn != null) {
getTableView().edit(getTableRow().getIndex(),
nextColumn);
}
});
datePicker.focusedProperty().addListener(
new ChangeListener<Boolean>() {
#Override
public void changed(
ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) {
if (!arg2) {
commitEdit(datePicker.getValue());
}
}
});
datePicker.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent t) {
// System.out.println("setOnKeyPressed datapicker get value ...." + t.getCode());
/* if (t.getCode() == KeyCode.ENTER) {
commitEdit(datePicker.getValue());
System.out.println("Enter datapicker get value " + datePicker.getValue());
} else */if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
} else if (t.getCode() == KeyCode.ENTER){
commitEdit(datePicker.getValue());
// System.out.println("Tab datapicker get value " + datePicker.getValue());
TableColumn nextColumn = getNextColumn(!t.isShiftDown());
// System.out.println("nextColumn datapicker get value " + nextColumn.getId());
if (nextColumn != null) {
getTableView().edit(getTableRow().getIndex(),
nextColumn);
}
}
}
});
addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.TAB) {
commitEdit(LocalDate.parse(datePicker.getEditor().getText(), DateTimeFormatter.ofPattern("dd/MM/yyyy")));
TableColumn nextColumn = getNextColumn(true);
if (nextColumn != null) {
getTableView().edit(getTableRow().getIndex(),
nextColumn);
}
}
}
});
//
// // setAlignment(Pos.CENTER);
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText(getItem().toString());
setGraphic(null);
}
public DatePicker getDatePicker() {
return datePicker;
}
public void setDatePicker(DatePicker datePicker) {
this.datePicker = datePicker;
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
private TableColumn<Deduction, ?> getNextColumn(boolean forward) {
List<TableColumn<Deduction, ?>> columns = new ArrayList<>();
for (TableColumn<Deduction, ?> column : getTableView().getColumns()) {
columns.addAll(getLeaves(column));
}
// There is no other column that supports editing.
if (columns.size() < 2) {
return null;
}
int currentIndex = columns.indexOf(getTableColumn());
int nextIndex = currentIndex;
if (forward) {
nextIndex++;
if (nextIndex > columns.size() - 1) {
nextIndex = 0;
}
} else {
nextIndex--;
if (nextIndex < 0) {
nextIndex = columns.size() - 1;
}
}
return columns.get(nextIndex);
}
private List<TableColumn<Deduction, ?>> getLeaves(
TableColumn<Deduction, ?> root) {
List<TableColumn<Deduction, ?>> columns = new ArrayList<>();
if (root.getColumns().isEmpty()) {
// We only want the leaves that are editable.
if (root.isEditable()) {
columns.add(root);
}
return columns;
} else {
for (TableColumn<Deduction, ?> column : root.getColumns()) {
columns.addAll(getLeaves(column));
}
return columns;
}
}
}
in your class with the tableview
Callback cellFactoryDate
= new Callback<TableColumn, TableCell>() {
public TableCell call(TableColumn p) {
return new DatePickerCell(p);//DatePickerTest(p) //DatePickerTest2 //EditingCellDate
}
};
dateColumn.setCellValueFactory(new PropertyValueFactory<>("date"));
// dateColumn.setCellFactory(cellFactoryTest);//cellFactoryDate
dateColumn.setCellFactory(cellFactoryDate);
dateColumn.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Deduction, LocalDate>>() {
#Override
public void handle(TableColumn.CellEditEvent<Deduction, LocalDate> t) {
((Deduction) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setDate(t.getNewValue());
}
}
);
Here is a solution acceptable for all custom controls; this example use a ColorPicker control:
So finnaly I deal it like that: on the events of the controls I get back the POJO objects in use by the "((Inputs)getTableView().getItems().get(getTableRow().getIndex()" and I update similary like is it done in the OnEditCommit method...
So for me it's look like this (update the color):
((Inputs) getTableView().getItems().get(
getTableRow().getIndex())
).setColor(cp.getValue());
Here is example with ColorPickerCell
:
public class ColorPickerTableCell<Inputs> extends TableCell<Inputs, Color>{
private ColorPicker cp;
public ColorPickerTableCell(){
cp = new ColorPicker();
cp.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
commitEdit(cp.getValue());
updateItem(cp.getValue(), isEmpty());
((Inputs) getTableView().getItems().get(
getTableRow().getIndex())
).setColor(cp.getValue());
}
});
setGraphic(cp);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setEditable(true);
}
#Override
protected void updateItem(Color item, boolean empty) {
super.updateItem(item, empty);
cp.setVisible(!empty);
this.setItem(item);
cp.setValue(item);
}
}
With this simple JavaFX's POJO:
public ObjectProperty<Color> color = new SimpleObjectProperty<Color>();
this.color = new SimpleObjectProperty(color);
public ObjectProperty<Color> colorProperty() {
return color;
}
public void setColor(Color color2) {
color.set(color2);
}
I do not know if it's a good way to achive that but it worked for me... Note that the JavaFX's POJO is only accessible within an "ActionEvent" request (combobox, datepicker, colorpicker, etc..)
Regards,