I have created a cell table with checkbox cell in each column. But when i click on any cell, all check boxes are getting selected. My actual requirement is i want to create child parent relationship in checkbox cells in a row i. e. first column will have checkbox and second column will have its multiple children checkboxes and third will have children for each checkbox from second column. I want to select all children on parent selection and if any child gets unselected parent also should get unselected. Parent will remain selected only if its all children are selected.
Please give me a solution. Thanks in advance.
Code is as follows
final SelectionModel<ContactInfo> selectionModel = new MultiSelectionModel<ContactInfo>();
cellTable.setSelectionModel(selectionModel,
DefaultSelectionEventManager.<ContactInfo> createCheckboxManager(0));
Column<ContactInfo, Boolean> checkColumn = new Column<ContactInfo, Boolean>(new NamedCheckBoxCell(true, false)) {
#Override
public Boolean getValue(ContactInfo object) {
NamedCheckBoxCell namedCell = (NamedCheckBoxCell)this.getCell();
namedCell.setTextValue(object.getFirstName());
return selectionModel.isSelected(object);
}
};
cellTable.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("First Name"));
cellTable.setColumnWidth(checkColumn, 20, Unit.PCT);
cellTable.addCellPreviewHandler(DefaultSelectionEventManager.<ContactInfo> createCheckboxManager(1));
Column<ContactInfo, Boolean> firstNameColumn = new Column<ContactInfo, Boolean>(
new NamedCheckBoxCell(true, false)) {
#Override
public Boolean getValue(ContactInfo object) {
NamedCheckBoxCell namedCell = (NamedCheckBoxCell)this.getCell();
namedCell.setTextValue(object.getLastName());
// Get the value from the selection model.
return selectionModel.isSelected(object);
}
};
cellTable.addColumn(firstNameColumn, "Last Name");
cellTable.setColumnWidth(firstNameColumn, 20, Unit.PCT);
cellTable.addCellPreviewHandler(DefaultSelectionEventManager.<ContactInfo> createCheckboxManager(2));
// Last name.
Column<ContactInfo, Boolean> lastNameColumn = new Column<ContactInfo, Boolean>(
new NamedCheckBoxCell(true, false)) {
#Override
public Boolean getValue(ContactInfo object) {
NamedCheckBoxCell namedCell = (NamedCheckBoxCell)this.getCell();
namedCell.setTextValue(object.getAddress());
return selectionModel.isSelected(object);
}
};
lastNameColumn.setSortable(true);
cellTable.addColumn(lastNameColumn, "Address");
cellTable.setColumnWidth(lastNameColumn, 20, Unit.PCT);
Related
I have created a Table and for one of the columns with index 2 which is having a JPanel with multiple JCheckBox. I have set cell editor CheckBoxCellEditor to select and edit the checkbox.
When I select one checkbox from panel, the cell editor is calling getTableCellEditorComponent() and returning the component which is fine.
But when I select another column with index 1, instead of calling TableCellListener, getCellEditorValue() of cell editor is getting called and returning the value. Hence I am not able to capture the checkbox in column 1.
Code: Cell editor
class CheckBoxCellEditor extends AbstractCellEditor implements TableCellEditor{
JPanel panel = new JPanel(new FlowLayout());
AI38DataModel dataModel;
#Override
public Object getCellEditorValue() {
return values;
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if(value!=null){
//panel.removeAll();
List<AI38BetModelTable> modelList = dataModel.getModelList();
LinkedHashMap<String, JPanel> elePanelMap = dataModel.getElePanelMap();
if(modelList!=null || !modelList.isEmpty() || !elePanelMap.isEmpty()){
AI38BetModelTable model = modelList.get(row);
String key = dataModel.getPanelEleStringKey(model.getSelectedEvent().getEventCode(), model.getSelectedBetCode(), model.getElement(), (Set<Integer>)value);
panel = elePanelMap.get(key);
}
}
values = (Set<Integer>)value;
return panel;
}
Main class:
CheckBoxCellEditor CBCEditor = new CheckBoxCellEditor();
infoTable.getColumnModel().getColumn(2).setCellEditor(CBCEditor);
Table cell listener :
AbstractAction action = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
TableCellListener tcl = (TableCellListener) e.getSource();
AI38BetModelTable model = modelList.get(tcl.getRow());
Integer betCode = model.getSelectedBetCode();
Integer eventCode = model.getSelectedEvent().getEventCode();
if(tcl.getRow()==1){
boolean isReporting = (boolean) tcl.getNewValue();
}
}
};
TableCellListener tcl = new TableCellListener(infoTable, action);
selected check box in column 3 - this operation is calling getTableCellEditorComponent
then clicked on checkbox in column 2 - This operation instead of calling TableCellListener , calling the getCellEditorValue of cell editor
enter image description here
I have a cell table with the first column as checkboxes. My checkboxes have to be checked or unchecked when there is any single click event on the entire row. This is the following code for creating a MultiSelectionModel, creating CheckboxCell and creating a column for cell table.
MultiSelectionModel<Object> selectionModel = new MultiSelectionModel<>();
table.setSelectionModel(selectionModel);
CheckboxCell selectedCell = new CheckboxCell();
Column<Object,Boolean> selectedCol = new Column<Object, Boolean>(selectedCell){
#Override
public Boolean getValue(Object object) {
return object.isSelected();
}
};
table.addColumn(selectedCol);
//Single Click Event to Enable/Disable checkbox.
table.addDomHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Set<Object> selectedItems = selectionModel.getSelectedSet();
for (Object s : selectedItems) {
Window.alert(String.valueOf(s));
selectionModel.setSelected(s, true);
}
}
}, ClickEvent.getType());
I tried to mark a row as checked using "selectionModel.setSelected(s, true)". But it isn’t working, when I clicked on row, the corresponding checkbox is not being checked.
My question is how do I enable/disable checkboxes onclick of an entire row. Is my approach correct. Or Is there any other way to perform this action in GWT.
You are very close to the working solution.
In the selectedCell you should return the value depending on selectionModel:
return selectionModel.isSelected(object);
This way you are using default multi selection model that selects rows by clicking on them. And the checkbox value comes from the selection model. That's it.
See the working example below:
CellTable<String> table = new CellTable<String>();
final MultiSelectionModel<String> selectionModel = new MultiSelectionModel<>();
table.setSelectionModel(selectionModel);
CheckboxCell selectedCell = new CheckboxCell();
Column<String, Boolean> selectedCol = new Column<String, Boolean>(selectedCell) {
#Override
public Boolean getValue(String object) {
// return object.isSelected();
return selectionModel.isSelected(object);
}
};
table.addColumn(selectedCol);
table.addColumn(new TextColumn<String>() {
#Override
public String getValue(String object) {
return object;
}
});
List<String> values = new ArrayList<>();
for(int i = 0; i < 10; i++)
values.add("Line " + (i + 1));
table.setRowData(values);
You can use standard Ctrl and Shift keys to control selection.
I made a custom listview, following is the code:
ListView<Sector> sectorList = new ListView();
sectorList.setStyle("-fx-font-size: 21px;");
sectorList.setItems(data2);
sectorList.setCellFactory(new Callback<ListView<Sector>, ListCell<Sector>>() {
#Override
public ListCell<Sector> call(ListView<Sector> param) {
return new XCell();
}
});
.
class XCell extends ListCell<Sector>{
#Override
protected void updateItem(Sector sector, boolean empty){
super.updateItem(sector, empty);
if(!empty){
CheckBox checkbox = new CheckBox(sector.getName());
checkbox.setStyle("-fx-font-weight: bold;");
checkbox.setSelected(true);
Label label = new Label(" "+sector.getDescription());
label.setStyle("-fx-font-style: italic;");
VBox root = new VBox(5);
root.setPadding(new Insets(8));
root.getChildren().addAll(checkbox,label);
setGraphic(root);
}else{
setGraphic(null);
}
}
}
Is there a way to loop through the listview's items and check if the checkbox is selected or not? How?
There is isSelected() method in JavaFX for the same.
You could add a CheckBox field to Sector and assign it in the updateItem method:
sector.setCheckBox(checkbox);
You can then iterate through all the elements in your ListView:
sectorList.getItems().forEach((sector) -> {
boolean selected = sector.getCheckBox().isSelected();
// do whatever needs to be done
})
Update
You could also add a BooleanProperty to Sector and bind it to the selectedProperty of the CheckBox like this:
checkbox.selectedProperty().bind(selector.yourBooleanProperty);
And the check this property in the foreach loop
i hava a CheckboxTableViewer which has 10 columns, and the table is filled from database,
and i have a button outside the table named as "Delete",
what i want to do is:-
when i select rows using check box (multiple selection also) and when i press the "delete" button , i want the selected rows should get deleted from the database, and the tableviewer shuold get refreshed.
am pasting my tableviewer code below:-
final CheckboxTableViewer dataTable = CheckboxTableViewer.newCheckList(TableComposite2, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.BORDER |SWT.DM_FILL_BACKGROUND|SWT.FULL_SELECTION);
dataTable .getTable().setHeaderVisible(true);
dataTable .getTable().setLinesVisible(true);
dataTable .setContentProvider(new ArrayContentProvider());
//Action Check box
TableColumn columnCHead=new TableColumn(dataTable .getTable(),SWT.NONE);
columnCHead.setText("Delete");
columnCHead.setWidth(50);
// setting column input
TableViewerColumn columnC=new TableViewerColumn(dataTable ,columnCHead);
columnC.setLabelProvider(new ColumnLabelProvider()
{
public String getText(Object Element)
{
return null;
}
});
TableColumn columnFS1Head=new TableColumn(dataTable .getTable(),SWT.NONE);
columnFS1Head.setText("SOURCE DIRECTORY");
columnFS1Head.setWidth(300);
TableViewerColumn columnFS1=new TableViewerColumn(dataTable ,columnFS1Head);
columnFS1.setLabelProvider(new ColumnLabelProvider()
{
public String getText(Object Element)
{
AgedFileMaster a=(AgedFileMaster)Element;
return a.getDIRECTORY_PATH();
}
enter code here});
......
and i have a button for delete operation,(outside the table),
when i press delete button, i want the selected rows to get deleted...
am beginner to SWT.
anyone please help......
Use addSelectionListener on your Button control to be notified when the button is pressed:
button.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent event)
{
// TODO handle delete here
}
});
You need to do two things to remove the data - first update your data model to remove the objects and secondly tell the table viewer that the model has changed.
You can do something like this:
dataTable.getTable().setRedraw(false); // Stop redraw during update
IStructuredSelection selection = (IStructuredSelection)dataTable.getSelection();
for (Iterator<?> iterator = selection.iterator(); iterator.hasNext(); )
{
Object selectedObject = iterator.next();
// TODO remove from data model array
// Tell table view the object has been removed
dataTable.remove(selectedObject);
}
dataTable.getTable().setRedraw(true); // Allow updates to be drawn
An alternative to calling dataTable.remove on each object is to call dataTable.refresh once at the end. There is also a variant of remove which accepts an array of objects.
TableViewerColumn actionsNameCol = new TableViewerColumn(viewer, column);
actionsNameCol.setLabelProvider(new ColumnLabelProvider(){
//make sure you dispose these buttons when viewer input changes
Map<Object, Button> buttons = new HashMap<Object, Button>();
#Override
public void update(ViewerCell cell) {
TableItem item = (TableItem) cell.getItem();
Button button;
if(buttons.containsKey(cell.getElement()))
{
button = buttons.get(cell.getElement());
}
else
{
button = new Button((Composite) cell.getViewerRow().getControl(),SWT.NONE);
button.setText("Remove");
buttons.put(cell.getElement(), button);
}
TableEditor editor = new TableEditor(item.getParent());
editor.grabHorizontal = true;
editor.grabVertical = true;
editor.setEditor(button , item, cell.getColumnIndex());
editor.layout();
}
});
Delete selected rows (multiple rows) from Table when button clicks (Database Connectivity)
//Java ArrayList class uses a dynamic array for storing the elements
List<String> id_list=new ArrayList<String>();
//Button Text:Selected Row Delete
Button btnNewButton = new Button(parent, SWT.NONE);
btnNewButton.setText("Selected Row Delete");
btnNewButton.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
TableItem[] item=table.getItems();
for(int i=0;i<table.getItemCount();i++)
{
if(item[i].getChecked()&&!item[i].getText(1).equals(""))
{
String id=item[i].getText(1);
id_list.add(id);//Add ID into List
}
}
for(int j=0;j<id_list.size();j++)
{
//class:Test
//Method:DeleteData(String ID) pass id to delete rows
// type cast object into string
Test.DeleteData((String) id_list.get(j));
}
}
});
btnNewButton.setImage(ResourceManager.getPluginImage("RCP_Demo", "icons/delete.png"));
btnNewButton.setBounds(18, 370, 68, 23);
Test.java
public class Test {
static Connection conn = null;
static PreparedStatement presta=null;
public static void DeleteData(String ID)
{
String url = "jdbc:sqlite:Demo.db";
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(url);
presta = conn.prepareStatement("delete from Student where sid=?");
presta.setString(1, ID);
presta.executeUpdate();
DisplayData();
}catch(Exception e)
{
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}//End DeleteData()
}//End Test class
I need to update the store when the checkbox in the grid cell changed its state: to add or to remove the value from store. how to handle this event?
BTW, I create the checkbox in grid in this way:
column = new ColumnConfig();
column.setId("accepted");
column.setHeader("Accepted");
column.setWidth(55);
UPD2: Now I do the following:
create checkboxes as firstly decided:
CheckColumnConfig checkColumn = new CheckColumnConfig("accepted", "", 55);
CellEditor checkBoxEditor = new CellEditor(new CheckBox());
checkBoxEditor.setToolTip("If you click here server will consider this rule checking your messages");
checkColumn.setEditor(checkBoxEditor);
checkColumn.setHeader("apply");
configs.add(checkColumn);
than handle events in the grid like this:
UPD3:
grid.addListener(Events.CellMouseUp, new Listener<GridEvent>() {
#Override
public void handleEvent(GridEvent be) {
PropertyItem item;
if (grid.getStore().getAt(be.getRowIndex()).isAccepted()){
item = new PropertyItem(val1, val2, val3, true);
} else {
item = new PropertyItem(val1, val2, val3, false);
}
store.update(item);
store.commitChanges();
saveProperties(store, customerId, toRemove);
}
});
this is the right way.
According to the docs found here, you can add a listener to the CellEditor's Complete event. In the Complete event Listener, perform whatever activity you need to accomplish.
Update:
Try the following
column.setRenderer(new GridCellRenderer() {
#Override
public Object render(ModelData model, String property, ColumnData config, int rowIndex, int colIndex, final ListStore store, Grid grid) {
CheckBox box = new CheckBox();
box.addListener(Events.Change, new Listener<FieldEvent>() {
#Override
public void handleEvent(FieldEvent be) {
st.commitChanges();
saveProperties(st, customerId, toRemove);
// I'm not sure what saveProperties is, but see if this works now.
// this event should DEFINITELY be fired when the checkbox is clicked
// so if it doesn't work, try changing how you do your code here
// maybe by doing model.set(property, (Boolean) be.getValue()); or something
}
});
return box;
}
});