How to remove the last character in a JTextField when delete key is pressed - jtextfield

I want to use a key listener to detected each time the user enters text into a field. Each time the key event is triggered I want to get the length() of the text in the JTextField. If the length >= limit then I want to disable editing. However, if the delete key is pressed I want to remove the last character in the JTextField and setEditable(true).
How do I remove the last character in the JTextField?
public void keyPressed (KeyEvent evt) {}
public void keyReleased (KeyEvent evt) {
int limit = 1;
JTextField text = (JTextField)evt.getSource();
if (text.getText().length() >= limit) {
text.setEditable(false);
}
else {
if (evt.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
answer ="";
text.setEditable(true);
}
public void keyTyped (KeyEvent evt) {}
}

Try wrapping the entire event handler in a SwingUtilities.invokeLater block.
public void keyReleased(KeyEvent evt)
{
final int limit = 1;
final int keyCode = evt.getKeyCode();
final JTextField text = (JTextField)evt.getSource();
SwingUtilities.invokeLater(new Runnable(){
public void run() {
if (text.getText().length() >= limit)
{
text.setEditable(false);
}
else if(keyCode == KeyEvent.VK_BACK_SPACE)
{
answer ="";
text.setEditable(true);
}
}
});
}
Since event handling and Swing GUI updates are both done on the Event Dispatch Thread, this may be needed to allow the text.getText() method to retrieve all of the entered text.

Related

JAVAFX - Tableview with modifiable custum TimePicker cell close too quickly

I have a Tableview with modifiable custum TimePicker cell.
I wrote a function that listens the changes in that cell but when I click on a specific hour, the clock doesn't stay open and close at the first click and i have to click again to select the minutes for exemple.
How can i let the clock open and make the editCommitEvent() when the clock close?
Thank you for your help :)
Here is the code of my custum cell.
PS: I use jfoenix TimePicker
public class TimePickerTableCell<Patient> extends TableCell<Patient, LocalTime> {
private JFXTimePicker timePicker;
private boolean listening = true;
// listener for changes in the timePicker
#SuppressWarnings({ "unchecked", "rawtypes" })
private final ChangeListener<LocalTime> listener = (observable, oldValue, newValue) -> {
if (listening) {
listening = false;
TableColumn<Patient, LocalTime> column = getTableColumn();
EventHandler<TableColumn.CellEditEvent<Patient, LocalTime>> handler = column.getOnEditCommit();
if (handler != null) {
// use TableColumn.onEditCommit if there is a handler
handler.handle(new TableColumn.CellEditEvent<>(
(TableView<Patient>) getTableView(),
new TablePosition<Patient, LocalTime>(getTableView(), getIndex(), column),
TableColumn.<Patient, LocalTime>editCommitEvent(),
newValue
));
} else {
// otherwise check if ObservableValue from cellValueFactory is
// also writable and use in that case
ObservableValue<LocalTime> observableValue = column.getCellObservableValue((Patient) getTableRow().getItem());
if (observableValue instanceof WritableValue) {
((WritableValue) observableValue).setValue(newValue);
}
}
listening = true;
}
};
public TimePickerTableCell () {
this.timePicker = new JFXTimePicker();
this.timePicker.valueProperty().addListener(listener);
this.timePicker.setOnMouseEntered((event)->{timePicker.requestFocus();timePicker.show();System.err.println("OUVERTURE TIMEPICKER");});
this.timePicker.setOnMouseExited((event)->{if(event.getY()<23)timePicker.hide();});
}
#Override
protected void updateItem(LocalTime item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
listening = false;
setGraphic(null);
} else {
listening = false;
setGraphic(this.timePicker);
this.timePicker.setValue(item);
this.timePicker.getStyleClass().add("time-picker");
listening = true;
}
}
public static <E> Callback<TableColumn<E, LocalTime>, TableCell<E, LocalTime>> forTableColumn() {
return column -> new TimePickerTableCell<>();
}
}
First, the reason the JFXTimePicker hides when you go to click the clock is (most likely) because of your onMouseExited handler. When you move your mouse over the popup it "exits" the JFXTimePicker and thus hides the clock.
You're also implementing an editable TableCell the wrong way. You should be overriding the startEdit() and cancelEdit() methods of the Cell class (which TableCell inherits from). You can look at the source code of classes like TextFieldTableCell for how it's done. I also worked up an example for doing this with JFXTimePicker:
import com.jfoenix.controls.JFXTimePicker;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.input.KeyCode;
import javafx.util.Callback;
import javafx.util.converter.LocalTimeStringConverter;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class TimePickerTableCell<S> extends TableCell<S, LocalTime> {
// Static methods for creating TableColumn.cellFactory Callbacks
public static <S> Callback<TableColumn<S, LocalTime>, TableCell<S, LocalTime>> forTableColumn() {
return v -> new TimePickerTableCell<>();
}
public static <S> Callback<TableColumn<S, LocalTime>, TableCell<S, LocalTime>> forTableColumn(DateTimeFormatter formatter) {
return v -> new TimePickerTableCell<>(formatter);
}
// Formatter property
private final ObjectProperty<DateTimeFormatter> formatter = new SimpleObjectProperty<>(this, "formatter");
public final void setFormatter(DateTimeFormatter formatter) { this.formatter.set(formatter); }
public final DateTimeFormatter getFormatter() { return formatter.get(); }
public final ObjectProperty<DateTimeFormatter> formatterProperty() { return formatter; }
// JFXTimePicker field
private JFXTimePicker timePicker;
// Constructors
public TimePickerTableCell() {
this(DateTimeFormatter.ISO_LOCAL_TIME);
}
public TimePickerTableCell(DateTimeFormatter formatter) {
getStyleClass().add("time-picker-table-cell");
setFormatter(formatter);
}
// Display logic
#Override
protected void updateItem(LocalTime item, boolean empty) {
super.updateItem(item, empty);
setGraphic(null);
if (empty || item == null) {
setText(null);
} else {
setText(formatItem(item));
}
}
private String formatItem(LocalTime item) {
if (item == null) {
return null;
}
return getFormatter() == null ? item.toString() : getFormatter().format(item);
}
// Edit logic
#Override
public void startEdit() {
if (!isEditable() ||
!getTableColumn().isEditable() ||
!getTableView().isEditable()) {
return;
}
super.startEdit();
if (isEditing()) {
if (timePicker == null) {
createTimePicker();
}
timePicker.setValue(getItem());
setText(null);
setGraphic(timePicker);
// Wrapped this in a Platform#runLater call because otherwise
// I couldn't get this to work properly. Despite this, there are
// times where this still seems buggy.
Platform.runLater(() -> {
timePicker.requestFocus();
timePicker.getEditor().selectAll();
});
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText(formatItem(getItem()));
setGraphic(null);
}
private void createTimePicker() {
timePicker = new JFXTimePicker();
timePicker.setConverter(new LocalTimeStringConverter(getFormatter(), null));
formatter.addListener((observable, oldValue, newValue) ->
timePicker.setConverter(new LocalTimeStringConverter(newValue, null)));
timePicker.getEditor().setOnKeyReleased(event -> {
if (event.getCode() == KeyCode.ENTER) {
commitEdit(timePicker.getValue());
event.consume();
} else if (event.getCode() == KeyCode.ESCAPE) {
cancelEdit();
event.consume();
}
});
timePicker.focusedProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue) {
cancelEdit();
}
});
}
}
Here, if the ESCAPE key is released or if the JFXTimePicker loses focus then the edit is cancelled. It appears that interacting with the clock does not cause the JFXTimePicker to lose focus (at least when I tried it).
If you want to commit the edit you have to press the ENTER key. This works (again, at least when I tried it) even if the clock is currently showing.
This doesn't commit the edit automatically when the clock closes but you should be able to add that behavior if desired. Since JFXTimePicker extends from ComboBoxBase it has properties such as onHiding and onHidden.
Note: If, after typing the time manually, you attempt to commit and the DateTimeFormatter is unable to parse the String it simply reverts to the old value. There is no indication of any error other than the fact the value hasn't changed. This seems to be behavior caused by the JFXTimePicker, however.
You also don't need to try and handle committing the value yourself, either. The TableColumn already attempts to set the new value on the underlying property by default. This is mentioned in the Javadoc of TableView (under the "Editing" header, emphasis mine):
When you call Cell.commitEdit(Object) an event is fired to the
TableView, which you can observe by adding an EventHandler via
TableColumn.setOnEditCommit(javafx.event.EventHandler). Similarly, you
can also observe edit events for edit start and edit cancel.
By default the TableColumn edit commit handler is non-null, with a
default handler that attempts to overwrite the property value for the
item in the currently-being-edited row. It is able to do this as the
Cell.commitEdit(Object) method is passed in the new value, and this is
passed along to the edit commit handler via the CellEditEvent that is
fired. It is simply a matter of calling
TableColumn.CellEditEvent.getNewValue() to retrieve this value.
If you do end up using your own EventHandler in setOnEditCommit then you need to implement the behavior yourself:
It is very important to note that if you call
TableColumn.setOnEditCommit(javafx.event.EventHandler) with your own
EventHandler, then you will be removing the default handler. Unless
you then handle the writeback to the property (or the relevant data
source), nothing will happen. You can work around this by using the
TableColumnBase.addEventHandler(javafx.event.EventType,
javafx.event.EventHandler) method to add a
TableColumn.editCommitEvent() EventType with your desired EventHandler
as the second argument. Using this method, you will not replace the
default implementation, but you will be notified when an edit commit
has occurred.

Restrict user to give input up to 3 characters in javafx

I am new to javaFx so please ignore my silly question here I want to validate (restrict) user to give 3 characters input (if user put more input, it should not allowed or after 3 characters, no latter should be visible) I found many solutions for validation but it does not restricting up to 3 characters as well as it little confusing to understand Here is my code.
public class editController {
#FXML
private TextField countrycode;
public void add(ActionEvent event) {
String ADD=countrycode.getText();
try {
if(ADD.isEmpty()){
Alert alert=new Alert(Alert.AlertType.ERROR);
alert.setHeaderText(null);
alert.setContentText("Please Fill All DATA");
alert.showAndWait();
return;
}
FXMLLoader loader =new FXMLLoader();
loader.load(getClass().getResource("/region/newCountry.fxml").openStream());
Validate using textProperty Listener like:
countrycode.textProperty().addListener(new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (newValue.length() > 3) {
countrycode.setText(oldValue);
}
}
});
Or get a String length and check that like
int length = ADD.length();
if (length > 3) {
System.out.println("Please Enter Lessthen 3 character");
}
you have to #Override the replaceText(int,int,String) method of your textField this way:
#Override
public void replaceText(int start, int end, String text) {
if ("".equals(text)) { // handles delete
super.replaceText(start, end, text);
return;
}
if (getText().length() < 3) { // handles add and checks length.
super.replaceText(start, end, text);
}
}
This won't let you to insert more than 3 characters, but you can define any regexp and use instead of the second if condition.
The solution of #KeyurBhanderi is good enough until you are typing char by char. But when you try to paste from the clipboard a long text you will not see any changes in the text field. Surprise!
As alternative to avoid confusing set at least truncated string:
field.setText(newValue.substring(0, maxLimit));
In this case the end user will see a part of text and will quickly understand what is going on. Even better to show a popup window with a warning.

JavaFX Spinner change is slow with click and hold of mouse button

The speed of Spinner update is slow when I click and hold the up/down arrow buttons. Is there a way to increase the change speed?
When I click, click, click with the mouse, the spinner values change as fast as I click. It also changes fast if I use the up/down arrows on the keyboard for each key press or if I hold down the up/down arrow keys. I want the values to change that fast when I click and hold on the arrow buttons.
Anyone know a way to do that?
The SpinnerBehavior of the SpinnerSkin triggers updates every 750 ms. Unfortunately there is no way to simply set/modify this behavour without using reflection to access private members. Therefore the only way to do this without reflection is using event filters to trigger the updates at a faster rate:
private static final PseudoClass PRESSED = PseudoClass.getPseudoClass("pressed");
#Override
public void start(Stage primaryStage) {
Spinner<Integer> spinner = new Spinner(Integer.MIN_VALUE, Integer.MAX_VALUE, 0);
class IncrementHandler implements EventHandler<MouseEvent> {
private Spinner spinner;
private boolean increment;
private long startTimestamp;
private static final long DELAY = 1000l * 1000L * 750L; // 0.75 sec
private Node button;
private final AnimationTimer timer = new AnimationTimer() {
#Override
public void handle(long now) {
if (now - startTimestamp >= DELAY) {
// trigger updates every frame once the initial delay is over
if (increment) {
spinner.increment();
} else {
spinner.decrement();
}
}
}
};
#Override
public void handle(MouseEvent event) {
if (event.getButton() == MouseButton.PRIMARY) {
Spinner source = (Spinner) event.getSource();
Node node = event.getPickResult().getIntersectedNode();
Boolean increment = null;
// find which kind of button was pressed and if one was pressed
while (increment == null && node != source) {
if (node.getStyleClass().contains("increment-arrow-button")) {
increment = Boolean.TRUE;
} else if (node.getStyleClass().contains("decrement-arrow-button")) {
increment = Boolean.FALSE;
} else {
node = node.getParent();
}
}
if (increment != null) {
event.consume();
source.requestFocus();
spinner = source;
this.increment = increment;
// timestamp to calculate the delay
startTimestamp = System.nanoTime();
button = node;
// update for css styling
node.pseudoClassStateChanged(PRESSED, true);
// first value update
timer.handle(startTimestamp + DELAY);
// trigger timer for more updates later
timer.start();
}
}
}
public void stop() {
timer.stop();
button.pseudoClassStateChanged(PRESSED, false);
button = null;
spinner = null;
}
}
IncrementHandler handler = new IncrementHandler();
spinner.addEventFilter(MouseEvent.MOUSE_PRESSED, handler);
spinner.addEventFilter(MouseEvent.MOUSE_RELEASED, evt -> {
if (evt.getButton() == MouseButton.PRIMARY) {
handler.stop();
}
});
Scene scene = new Scene(spinner);
primaryStage.setScene(scene);
primaryStage.show();
}
I modified the answer of fabian a little bit to decrease the speed of the spinner while holding mouse down:
private int currentFrame = 0;
private int previousFrame = 0;
#Override
public void handle(long now)
{
if (now - startTimestamp >= initialDelay)
{
// Single or holded mouse click
if (currentFrame == previousFrame || currentFrame % 10 == 0)
{
if (increment)
{
spinner.increment();
}
else
{
spinner.decrement();
}
}
}
++currentFrame;
}
And after stopping the timer we adjust previousFrame again:
public void stop()
{
previousFrame = currentFrame;
[...]
}
A small improvement to Fabian's answer. Making the following mod to the MOUSE_RELEASED addEventerFilter will stop a NullPointerException caused when clicking the textfield associated with the spinner. Cheers Fabian!
spinner.addEventFilter(MouseEvent.MOUSE_RELEASED, evt -> {
Node node = evt.getPickResult().getIntersectedNode();
if (node.getStyleClass().contains("increment-arrow-button") ||
node.getStyleClass().contains("decrement-arrow-button")) {
if (evt.getButton() == MouseButton.PRIMARY) {
handler.stop();
}
}
});
An alternative to changing the update speed might in some cases be adjusting the amount by which the value increments/decrements per update.
SpinnerValueFactory.IntegerSpinnerValueFactory intFactory =
(SpinnerValueFactory.IntegerSpinnerValueFactory) spinner.getValueFactory();
intFactory.setAmountToStepBy(100);
Reference: http://news.kynosarges.org/2016/10/28/javafx-spinner-for-numbers/

Deleting multiple rows from TableView

#FXML
private void handleDeleteAction(ActionEvent event) {
for (Transaction transaction : transactionsTable.getSelectionModel().getSelectedItems()) {
RemoveTransactionsCommand removeTransactionsCommand = new RemoveTransactionsCommand(transaction, transactionsTable.getSelectionModel().getSelectedItems(), data);
commandRegistry.executeCommand(removeTransactionsCommand);
}
}
Why it won't work in case where I select more than one row, I mean it delete one row (sometimes two, but can't find what decide about it)
Here is command implementation:
public class RemoveTransactionsCommand implements Command {
private ObservableList<Transaction> selectedItems;
private Transaction transactionToRemove;
private Account account;
public RemoveTransactionsCommand(Transaction transactionToRemove, ObservableList<Transaction> selectedItems, Account account) {
this.account = account;
this.transactionToRemove = transactionToRemove;
this.selectedItems = selectedItems;
}
#Override
public String getName() {
int presentSize = selectedItems.size();
return presentSize + "transaction/s removed";
}
#Override
public void execute() {
account.removeTransaction(transactionToRemove);
}
}
And removal command:
public void removeTransaction(Transaction transaction) {
this.transactions.remove(transaction);
}
Additionally I wanted to know the size of actual delete operation but what I pass as a 2nd argument isn't static and for example when every row is deleted it will be 0.
Any advices how to improve it?
Full project can be found here
The problem is that the selected items list may change when the list of items in the table changes. So the list gets modified while you are trying to iterate through it.
You should create a copy of the list of selected items and iterate through it instead:
#FXML
private void handleDeleteAction(ActionEvent event) {
List<Transaction> selectedTransactions = new ArrayList<>(transactionTable.getSelectionModel().getSelectedItems());
for (Transaction transaction : selectedTransactions) {
RemoveTransactionsCommand removeTransactionsCommand = new RemoveTransactionsCommand(transaction, selectedTransactions, data);
commandRegistry.executeCommand(removeTransactionsCommand);
}
}
(and change the type of selectedItems in RemoveTransactionsCommand to List<Transaction>).

Why is JavaFX WebEngine getLoadWorker looping?

I'm not very sure how to word this question but I'll try. My application runs commands against a website with a click of a button. The issue is during each loop the getLoadWorker increases by 1. In the load worker i set listeners. Here is how it works.
MenuItem executeToHere = new MenuItem("Execute to here");
executeToHere.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
listViewStepItem item = stepListView.getSelectionModel().getSelectedItem();
int selectedIndex = stepList.getSelectionModel().getSelectedIndex();
WebBrowser browser = new WebBrowser(item.getWebView(), item.getListView());
for(int i=0; i < selectedIndex; i++){
listViewStepItem item2 = stepList.getItems().get(i);
if(item2.comboBoxSelected.contains("http://")){
browser.loadURL();
} else if(item2.comboBoxSelected.contains("enter")){
browser.enterText();
} else if(item2.comboBoxSelected.contains("click")){
browser.click();
}
}
browser.setWorker();
}
});
public class WebBrowser{
public WebBrowser(WebView fxmlWebView, WebEngine webEngine){
this.view = fxmlWebView;
this.engine = webEngine;
}
public void loadUrl(String url){
webEngine.load(url);
}
public void enterText(){
System.out.println("ENTER TEXT");
}
public void click(){
System.out.println("click");
}
public void setWorker(){
webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>(){
public void changed(ObservableValue ov, State oldState, State newState){
if(newState == javafx.concurrent.Worker.State.SUCCEEDED){
listener = new EventListener(){
public void handleEvent(org.w3c.dom.events.Event evt) {
eventListeners(evt);
}
};
setListenerByTagNames(listener, "a");
}
}
});
}
private void setListenerByTagNames(EventListener listener, String tagName){
Document doc = webEngine.getDocument();
NodeList elements = doc.getElementsByTagName(tagName);
for(int i=0; i < elements.getLength();i++){
((EventTarget) elements.item(i)).addEventListener("click", listener, false);
}
System.out.println("Listening on :"+tagName);
}
}
the first time i run it the output looks like this
ENTER TEXT
click
Listening on : a
second time
ENTER TEXT
click
Listening on : a
Listening on : a
third time
ENTER TEXT
click
Listening on : a
Listening on : a
Listening on : a
I don't see how the worker is increasing but it causes the page to reload/refresh somehow and therefore all the changes to the page DOM is reset.

Resources