I am fairly new in JavaFX. I have a table with multiple columns and an Edit button in each row. Whenever I click on the Edit 1st cell is selected for edit of that row. Everything goes fine but the problem is whenever I select a row and click on a cell of it also gets in edit mode though I have not clicked Edit. I think it's because I have made tableView.setEditable(true) but I want to enable edit only when I click Edit button and only for that row, not others when I double click/ single click. I have seen this but they have solved it by a pop-up. I don't want that.
In the initialize() method I tried this way but it's not working exactly. Can anyone show me the correct way to do this, please?
tableBuilding.setRowFactory(tv -> {
TableRow<ModelBrBuilding> row = new TableRow<>();
row.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> {
if (e.getButton() == MouseButton.SECONDARY) {
e.consume();
}
});
row.addEventFilter(MouseEvent.MOUSE_PRESSED,event -> {
if ( event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2 ) {
event.consume();
}
});
return row ;
});
and my button action looks like
EditButton.setOnAction((ActionEvent event)->{
TableRow row = cell.getTableRow();
tableBuilding.requestFocus();
tableBuilding.getSelectionModel().select(row.getIndex());
int i=tableBuilding.getSelectionModel().getSelectedIndex();
tableBuilding.edit(i,colName);
});
There may be a more elegant solution to this, but you could simply set the TableView editable right before you call tableView.edit(int, TableColumn) and then set it back to not being editable when the edit is either committed or cancelled. Or you can do this set\unset editable thing on each specific TableColumn.
For instance, in your Button's action handler:
button.setOnAction(evt -> {
evt.consume();
tableView.requestFocus();
tableView.edit(-1, null); // cancel any current edit if there is one
tableView.getSelectionModel().select(tableCell.getIndex());
tableView.setEditable(true);
tableView.edit(tableCell.getIndex(), tableColumn);
});
And then for the TableColumn:
EventHandler<TableColumn.CellEditEvent<S, T>> handler = evt -> tableView.setEditable(false);
tableColumn.setOnEditCancel(handler);
tableColumn.setOnEditCommit(handler);
// or you can use the addEventHandler(EventType, EventHandler) method
Related
I have a TreeView, when I select an item, a tab opens with the corresponding information.
But when I close the tab and try to open it, it does not appear because the item has already been selected. And I need to first select another, and then click on it again.
I use this.
fileView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue == null)
return;
System.out.println("Selected File : " + newValue.getValue().getAbsolutePath());
if (newValue.getValue().isFile()) {
...
}
});
I see 2 solutions to the problem.
1) remove the selection label from the item
2) replace the listener
But I didn’t succeed.
I will be glad to your solutions.
Please provide a code snippet for example
P.s. please do not lower my reputation, I'm really interested in my question
You can clear the selection after opening a tab:
fileView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
System.out.println("Selected File : " + newValue.getValue().getAbsolutePath());
if (newValue.getValue().isFile()) {
// Open a tab here...
/* Clear selection */
Platform.runLater(() -> fileView.getSelectionModel().clearSelection());
}
}
});
I'm trying to clear the selection when my table view loses focus. Right now, when I click on my add button, a new EMPTY row is added and I set it so the first column is on edit. If I click anywhere outside that cell, nothing happens. The cell remains selected which is not really what I want.
I'd prefer for the cell to become unselected when my tableview is unfocused.
I use a javafx.scene.control.TableView over a custom entry.
I tried setting on each column a setOnEditCancel but it doesn't work.
expressionTableColumn.setOnEditCancel(event -> {
final ObservableList<TableEntry> items = tableView.getItems();
if (items.contains(EMPTY_ENTRY)) {
items.remove(EMPTY_ENTRY);
}
tableView.getSelectionModel().clearSelection();
}
);
I'd prefer to clearSelection on table losing focus. Any ideas?
Add a ChangeListener to the focused property of Node (which TableView inherits). Then, when the new value of said property is false, retrieve the SelectionModel from the TableView's selectionModel property and call clearSelection().
tableView.focusedProperty().addListener((obs, oldVal, newVal) -> {
if (!newVal) {
tableView.getSelectionModel().clearSelection();
}
});
I have a GWT DataGrid with a multi-selection model and check-boxes to show selection/select/deselect rows. That's all well and good.
But, I also want to have a second, independent selection model. If a user double-clicks on a row, I want to handle that event, and for the event handler to know which row was double-clicked. The double-clicking should not affect the check-box selection.
I tried this:
final SelectionModel<MyRecord> selectionModel = new MultiSelectionModel...
//Yes I need a MultiSelectionModel
dataGrid.addDomHandler(new DoubleClickHandler() {
public void onDoubleClick(DoubleClickEvent event) {
selectionModel.get??? //no suitable getter for double-clicked
}
}, DoubleClickEvent.getType());
But ran into a dead-end when I found now way to get the double-clicked row in the event handler. One way would be to register both a Multi- and Single- selection model, but doubt DataGrid will support that.
Neither can I work out how to get the clicked row from the DoubleClickEvent object.
I have implemented a button cell with a FieldUpdater. This works, but it's not ideal.
Any suggestions?
If I understand correctly you want to get the index of the row.
You could do it like this: (this way you'll get the "Real" index)
AbstractSelectionModel<T> selectionModel = (AbstractSelectionModel<T>)dataGrid.getSelectionModel();
ArrayList<Integer> intList = new ArrayList<Integer>();
List<Row> list = (List<Row>)_dataProvider.getList();
int i = 0;
for(Row row : list)
{
if( selectionModel.isSelected(row) )
intList.add(i);
i++;
}
UPDATE:
To get only the current row you could do that:
datagrid.getKeyboardSelectedRow()
I'm 3 years too late to the party, but I think the more correct solution would be:
dataGrid.addCellPreviewHandler(new CellPreviewEvent.Handler<YOUR_MODEL_TYPE>() {
#Override
public void onCellPreview(final CellPreviewEvent<YOUR_MODEL_TYPE> event) {
if (BrowserEvents.DBLCLICK.equalsIgnoreCase(event.getNativeEvent().getType())) {
int row = event.getIndex();
doStuff(row); // do whatever you need the row index for
}
}
});
I'm trying to have a JTable edition working like in excel: if I start editing a cell, the cell becomes empty for receiving the new entry. The goal is to avoid the user having to delete the existing cell content first.
I can already detect cell start/stop edition by adding a PropertyChangeListener working as follow:
public void propertyChange(PropertyChangeEvent e)
{
// A cell has started/stopped editing
if ("tableCellEditor".equals(e.getPropertyName()))
{
if (table.isEditing())
processEditingStarted();
else
processEditingStopped();
}
}
Trying to clear the table model at processEditingStarted() does not work with the code bellow:
private void processEditingStarted()
{
SwingUtilities.invokeLater( this );
}
public void run()
{
row = table.convertRowIndexToModel( table.getEditingRow() );
column = table.convertColumnIndexToModel( table.getEditingColumn() );
oldValue = table.getModel().getValueAt(row, column);
newValue = null;
table.getModel().setValueAt(null, row, column);
table.updateUI();
}
However the editor content keeps the former value.
Does someone has clues to hide the current value of the cell during edition?
Optionnaly it should be able to restore the former cell content if the user did not actually modify the value.
I"ve never seen a spreadsheet remove data when you start editing a cell.
Table Select All Editor shows a different approach.
I did it like this. First I am using the event keyReleased and then getting the row and column number on which I am working and then setting the value at that row. Code goes like this.
private void purchases_TBLKeyReleased(java.awt.event.KeyEvent evt) {
int rowWorking = purchases_TBL.getSelectedRow();
int columnWorking = purchases_TBL.getSelectedColumn();
if(columnWorking==3){
model.setValueAt(null, rowWorking, columnWorking);
}
}
This makes the third column of the table null as soon as I focus move on to that using keyboard.
Note: The same piece of code can be placed in MouseClicked event.
What I'd like to do is be able to tab between elements in table.
I currently am creating my table like this.
this.tableViewer =
new TableViewer(parent , SWT.FULL_SELECTION);
tableViewer.setUseHashlookup(true);
table = tableViewer.getTable();
GridData gridData = new GridData(GridData.FILL_BOTH);
gridData.grabExcessVerticalSpace = true;
table.setLayoutData(gridData);
table.setLinesVisible(true);
table.setHeaderVisible(true);
...
/** Create the Cell Editor Array - will hold all columns **/
editors = new CellEditor[table.getColumnCount()];
/** Cell Editor Row 1 **/
/** Set the column properties **/
tableViewer.setColumnProperties(columnNames);
/** Assign the cell editors to the viewer **/
tableViewer.setCellEditors(editors);
/** Set the cell modifier for the viewer **/
tableViewer.setCellModifier(new MyCellModifier(this));
//Create the Table Viewer
/** Table Viewer Content and Label Provider **/
tableViewer.setContentProvider(new MyContentProvider(this));
tableViewer.setLabelProvider(new MyLabelProvider());
But I'm not sure how to set up the tabulation. Everything else works as far as editing columns, showing data, etc. Just stuck on this last part.
If I've missed obvious documentation or javadocs - my apologies and even pointing to those would be great.
Although the solution thehiatus posted is very low level and will probably work (I haven't tested it), JFace gives you a framework for this specific problem. See the org.eclipse.jface.viewers.TableViewerFocusCellManager along with org.eclipse.jface.viewers.CellNavigationStrategy classes to solve this problem.
I think by default tab does not jump from cell to cell in an swt table. Instead it traverses to the next control. So you'll also need to tell it not to traverse when tab is pressed
KeyListener keyListener = new KeyLisener()
{
public void keyPressed(KeyEvent evt)
{
if (evt.keyCode == SWT.TAB)
{
// There are numerous setSelection methods. I'll leave this to you.
tableViewer.getTable().setSelection(...)
}
}
public void keyReleased(KeyEvent evt){}
}
TraverseListener traverseListener = new TraverseListener()
{
public void keyTraversed(TraverseEvent evt)
{
if (evt.keyCode == SWT.TAB)
evt.doit = false;
}
}
tableViewer.getTable().addKeyListener(keyListener);
tableViewer.getTable().addTraverseListener(traverseListener);
Also, as derBiggi suggested, the listeners need to be added to the Table object, not the TableViewer.
I couldn't get the desired behavior with a TraverseListener (it would not traverse within the table), and I had trouble getting it to work with a FocusCellManager and CellNavigationStrategy. I finally found this solution that enables me to tab from column to column within a row and automatically activate the editor.
Viewer viewer = ...
TableViewerFocusCellManager focusCellManager =
new TableViewerFocusCellManager(
viewer,
new FocusCellHighlighter(viewer) {});
ColumnViewerEditorActivationStrategy editorActivationStrategy =
new ColumnViewerEditorActivationStrategy(viewer) {
#Override
protected boolean isEditorActivationEvent(
ColumnViewerEditorActivationEvent event) {
ViewerCell cell = (ViewerCell) event.getSource();
return cell.getColumnIndex() == 1 || cell.getColumnIndex() == 2;
}
};
TableViewerEditor.create(viewer, focusCellManager, editorActivationStrategy,
TableViewerEditor.TABBING_HORIZONTAL);
You need to add a KeyListener and set the selection or focus to the next cell:
tableViewer.getTable().addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed");
if (e.keycode == SWT.TAB)
{
System.out.println("Detected TAB key");
// set table viewer selection
}
}
public void keyReleased(KeyEvent e) {
System.out.println("Key Released");
}}
);
I also had to implement tabbing between elements in a table. We use Grid from Nebula as the table.
Firstly, I had to suppress tabbing the focus preventing it from moving out of the table.
and then I added a Key Listener which moves the focus/selection to the next cell:
I also made my own algorithm to move the selection one cell to the right and when at the end of the row, move it to the beginning of the next row. When end of table is reached, the selection moves back to the first cell in the table.
This solved the problem for me.