I have a table with many TableItems (Not a tableViewer), when I click on one of the table Items it get selected . The only way to deselect it is by selecting another TableItem. I want to implement a way to deselect The Table selection when The user click on the table Where there is no TableItems, or when ReSelecting the same TableItem.
table.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
if(e.item != ItemSelectioner ) {
ItemSelectioner = (TableItem)e.item;
// Blabla
}else {
ItemSelectioner = null;
table.deselectAll();
//blabla
}
}
});
As you can see, am using a selectionEvent which I think is the probleme, and using:
e.doit = false;
didn't work also.
Selection events are not generated for the empty parts of the table so you can't use a selection listener to do this.
You can use a mouse down listener and check if there is a table item at the mouse location:
table.addListener(SWT.MouseDown, event -> {
TableItem item = table.getItem(new Point(event.x, event.y));
if (item == null) { // No table item at the click location?
table.deselectAll();
}
});
To clear the selection the second time an item is clicked use something like this:
table.addListener(SWT.Selection, new Listener()
{
private int lastSelected = -1;
#Override
public void handleEvent(final Event event)
{
final int selectedIndex = table.getSelectionIndex();
if (selectedIndex < 0) {
lastSelected = -1;
return;
}
if (selectedIndex == lastSelected) {
table.deselect(selectedIndex);
lastSelected = -1;
}
else {
lastSelected = selectedIndex;
}
}
});
Related
I am Creating a tableview with 2 columns and each populated cell of this table is a ComboBox. This is how I am implementing this
private void loadTable() {
vBox.getChildren().clear();
this.tableView = new TableView<>();
tableView.setEditable(true);
TableColumn<CustomClass, Products> prodCol = createComboBoxColumn("products", "Product", Products.class,
productObList);
prodCol.setMinWidth(300);
prodCol.setOnEditCommit(e -> {
if (!e.getTableView().getItems().isEmpty()) {
System.out.println("e.getNewValue().getId(): " + e.getNewValue().getId());
Products product = productsModel.getProductsById(e.getNewValue().getId());
e.getTableView().getItems().get(e.getTablePosition().getRow()).setProducts(product);
}
tableView.refresh();
});
tableView.getColumns().add(prodCol);
TableColumn<CustomClass, Brand> brandCol = createComboBoxColumn("brand", "Brand", Brand.class,
brandObList);
brandCol.setMinWidth(300);
brandCol.setOnEditCommit(e -> {
if (!e.getTableView().getItems().isEmpty()) {
System.out.println("e.getNewValue().getId(): " + e.getNewValue().getId());
Brand brand = brandModel.getBrandById(e.getNewValue().getId());
e.getTableView().getItems().get(e.getTablePosition().getRow()).setBrand(brand);
}
tableView.refresh();
});
tableView.getColumns().add(brandCol);
// tableView.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
// #Override
// public void handle(MouseEvent event) {
// if (event.getClickCount() == 2) {
// System.out.println("on Click");
// if (event.getTarget() instanceof ComboBox) {
// System.out.println(((ComboBox) event.getTarget()).getSelectionModel().getSelectedItem());
// }
// }
// }
// });
tableView.getItems().addAll(brandManifestCustomObList);
vBox.getChildren().addAll(tableView);
}
and the createComboboxColumn Method as
public static <T> TableColumn<CustomClass, T> createComboBoxColumn(String name, String columHeading,
Class<T> type, ObservableList list) {
TableColumn<CustomClass, T> column = new TableColumn<>(columHeading);
column.setCellFactory(ComboBoxTableCell.forTableColumn(list));
column.setResizable(true);
column.setMaxWidth(100);
column.setEditable(true);
column.setCellValueFactory(new PropertyValueFactory<>(name));
return column;
}
What I am not able to achieve is to detect double click(or even single click) on the tablecell combo box. Once I select some other row and come back to this tablecell and doubleclick, only then I am able to detect the double click on the cell.
The obvious reason is once I click on a cell it becomes a Combobox and I have not written code to detect it, because I don't understand how to in this case.
Also, if possible, I need to detect the column index of the cell in the tableview.
Following questions do not answer what I am looking for:
1) JavaFx: ComboBox Table Cell double click
2) Detect mouse click on SELECTION Editable ComboBox JavaFX
3) Select JavaFX Editable Combobox text on click
Probably you can use
tableView.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getClickCount() == 2) {
System.out.println("on Click");
if (event.getTarget() instanceof ComboBox) {
System.out.println(((ComboBox) event.getTarget()).getSelectionModel().getSelectedItem());
}
if (event.getTarget() instanceof ComboBoxTableCell<?,?>) {
System.out.println(((ComboBoxTableCell) event.getTarget()).getItem().toString());
}
}
}
});
because the table cell has now changed to a ComboBoxTableCell.
To get the column of the tableView I got some idea from here given by James_D.
You can use
TablePosition pos = tableView.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
BrandManifestCustom bmc = tableView.getItems().get(row);
TableColumn col = pos.getTableColumn();
if (col.getCellObservableValue(bmc).getValue() instanceof Products) {
System.out.println("hey Products");
}
if (col.getCellObservableValue(bmc).getValue() instanceof Brand) {
System.out.println("hey Brand");
}
I've implemented a selection listener for my treeviewer to expand or collapse a node on selection.
This impementation works fine for collapsing, but does not expand a node.
this.getTree().addListener(SWT.Selection, new Listener() {
#Override
public void handleEvent(Event event) {
TreeItem treeItem = (TreeItem) event.item;
if (treeItem.getItems().length > 0) {
if (MyTreeViewer.this.getExpandedState(treeItem)) {
MyTreeViewer.this.collapseToLevel(treeItem, MyTreeViewer.this.ALL_LEVELS);
} else {
MyTreeViewer.this.expandToLevel(treeItem, 1);
}
MyTreeViewer.this.refresh();
}
}
});
Do you have any suggestions how to fix this?
For a JFace TreeViewer you should use a ISelectionChangedListener or a IDoubleClickListener - do not use the underlying Tree listeners as they may not interact correctly with the viewer.
This is what I use for double click:
public class TreeDoubleClickListener implements IDoubleClickListener
{
#Override
public void doubleClick(final DoubleClickEvent event)
{
IStructuredSelection selection = (IStructuredSelection)event.getSelection();
if (selection == null || selection.isEmpty())
return;
Object sel = selection.getFirstElement();
TreeViewer treeViewer = (TreeViewer)event.getViewer();
IContentProvider provider = treeViewer.getContentProvider();
if (provider instanceof ITreeContentProvider)
{
ITreeContentProvider treeProvider = (ITreeContentProvider)provider;
if (!treeProvider.hasChildren(sel))
return;
if (treeViewer.getExpandedState(sel))
treeViewer.collapseToLevel(sel, AbstractTreeViewer.ALL_LEVELS);
else
treeViewer.expandToLevel(sel, 1);
}
}
}
The key thing here is to use the selection as the argument to collapseToLevel / expandToLevel.
Just change to implement ISelectionChangedListener to work on selection.
Add the listener with TreeViewer addDoubleClickListener or addSelectionChangedListener
I have two JComboBoxes where the other one dynamically changing the value based on user choices. I properly get the id of those selected item. But getting the first element of my JComboBox gives me a zero value where I wanted to get the id without firing the ItemListener.
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if ("Add".equals(e.getActionCommand())) {
System.out.println("Position id is " + getPositionId());
}
}
}
ItemListener itemListener = new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == department) {
Department item = (Department) department.getSelectedItem();
int departmentId = item.getId();
model.setDeptId(departmentId);
List<Position> list = model.getAllPositionId();
DefaultComboBoxModel positionModel = new DefaultComboBoxModel(list.toArray());
position.setModel(positionModel);
}
else if (e.getSource() == position) {
Position item = (Position) cbPosition.getSelectedItem();
int positionId = item.getId();
model.setPositionId(positionId);
}
}
}
Every time the user changed the selected value. DefaultComboBoxModel changed also its value with corresponding id. But getting it returns me 0.
I already found a solution. I just created a void method outside the ItemListener where it gets the first element.
I have a JCombobox in which when I select any one from drop down list of JCombobox ,the selected item is opening but when I click on "Custom" among one of the drop down list I have to open a daiolg ,here daiolg is opening but drop down list is not closing I want to hide the drop down when I click on Custom. here is my sample code....
private PropertyChangeSupport pcs;///here Iam using ActionListener and PopupMenuListener
public void actionPerformed(ActionEvent ae){
if(ae.getSource() instanceof ComboBox )
{
ComboBox comboBox = (ComboBox)ae.getSource();
Object selectedItem = comboBox.getSelectedItem();
if(selectedItem != null && (!selectedItem.equals("(Custom..)")))
{
pcs.firePropertyChange("ITEM_SELECTED",getCaption(),null);
}}}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
{
ComboBox comboBox = (ComboBox)e.getSource();
Object repeatedSelectedItem = comboBox.getSelectedItem();
if(repeatedSelectedItem != null && repeatedSelectedItem.equals("(Custom..)"))
{
invokeCustomFilterDialog(repeatedSelectedItem, comboBox);
}}
private void invokeCustomFilterDialog(Object repeatedSelectedItem, ComboBox comboBox)
{
customFilterDialog.showDialog(); //here Iam opening dailog...
if(customFilterDialog.isCustomFilterAppliedFlag() == true)
{
pcs.firePropertyChange("ITEM_SELECTED",getCaption(),null);
}
else
{comboBox.setSelectedItem(lastSelectedItem);}}
public void popupMenuCanceled(PopupMenuEvent e)
{ }
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
ComboBox comboBox = (ComboBox)e.getSource();
this.lastSelectedItem = comboBox.getSelectedItem();
}
combobox.getUI().setPopupVisible(combobox, false);
You can use SwingUtilities.invokeLater.
For example
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
final JComboBox comboBox = (JComboBox) e.getSource();
final Object repeatedSelectedItem = comboBox.getSelectedItem();
if (repeatedSelectedItem != null
&& repeatedSelectedItem.equals("(Custom..)")) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
invokeCustomFilterDialog(repeatedSelectedItem, comboBox);
}
});
}
}
into something like this when I right click the row.after I clicked view profile it will popup and new jFrame and display his profile. i am using GUI builder. sorry for being noob. i'm still beginner.it's hard to find on google how to do right click thing.
UPDATE2
I created the menu now but how to get the Student ID cell only... this is my code
JMenuItem item = new JMenuItem("View Profile");
JMenuItem item2 = new JMenuItem("Delete");
item.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(studentList.this, "Testing");
}
});
jPopupMenu1.add(item);
jPopupMenu1.add(item2);
and on my MouseReleased
private void tableMouseReleased(java.awt.event.MouseEvent evt) {
int r = table.rowAtPoint(evt.getPoint());
if (r >= 0 && r < table.getRowCount()) {
table.setRowSelectionInterval(r, r);
} else {
table.clearSelection();
}
int rowindex = table.getSelectedRow();
if (rowindex < 0) {
return;
}
if (evt.isPopupTrigger() && evt.getComponent() instanceof JTable ) {
jPopupMenu1.show(evt.getComponent(), evt.getX(), evt.getY());
}
}
The easiest way would be to use JComponent#setComponentPopupMenu
You will also want to take a look at How to use menus