Adding button to the GXT Grid cell - java

I use GXT 2.2.0 and I need to make a button for deleting rows. It was an idea to make checkboxes and create a button "delete", but I already have checkbox for choosing rows by users to use them further and decided it is not "user-friendly". So how to add button to the cell?

to add the button to the cell I had to do this:
column = new ColumnConfig();
column.setRenderer(new GridCellRenderer() {
#Override
public Object render(ModelData model, String property, ColumnData config, int rowIndex, int colIndex, ListStore store, Grid grid) {
final int row = store.indexOf((PropertyItem) model);
Button b = new Button("remove", new SelectionListener<ButtonEvent>() {
#Override
public void componentSelected(ButtonEvent ce) {
Window.alert("row index= " + row);
remove(row, customerId);
}
});
b.setIconStyle("/gxt/images/gxt/icons/delete.png");
return b;
}
});

Related

A JComboBox in a specific cell in JTable

I would like to know how to set up a JComboBox in a particular cell in a JTable.
I have seen people using TableColumn setCellEditor(new DefaultCellEditor(comboBox)).
But this is for an entire column, I would like a specific cell.
So maybe I should do a custom TableCellEditor that would fit my needs, but I am a little lost on how to do it...
The goal of this is to manage filters on parameters. There are two kinds of filters:
The one that compares two values, for instance: number of balloons > 5
The one that will say is a value is inside a range of value, for instance: parameter name is inside {"one", "two", "three", "seven"}.
screenshot of my JTable:
As we can see in the picture, when there is the "comparator" "is among", we would need a JComboBox in cell[0][2] to choose the values of the range within a complete set of fields.
While cell[1][2] does not need a JComboBox, but just an editable cell.
I hope I have been clear and thank you for your help.
EDIT:
I was able to display a JComboBox only to realize, I couldn't select multiple values on it. So now I am trying to display a JList instead of a ComboBox.
But when I click on the cell, the JList is not displayed, I don't know why.
Here is my code:
JTable tableParametersFilter = new JTable(modelParametersFilter){
// Determine editor to be used by row
public TableCellEditor getCellEditor(int row, int column)
{
int modelColumn = convertColumnIndexToModel( column );
int modelRow = convertRowIndexToModel( row );
Parameter_Filter pf = view.listParameter_Filter.get(modelRow);
if(modelColumn == 2 && pf instanceof Parameter_Filter_To_List_Of_Fields) {
Parameter_Filter_To_List_Of_Fields pftlof = (Parameter_Filter_To_List_Of_Fields)pf;
JList<String> list = new JList<String>(pftlof.list_of_fields_total_names);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
list.setLayoutOrientation(JList.VERTICAL_WRAP);
list.setVisibleRowCount(-1);
return new TableCellEditor() {
#Override
public boolean stopCellEditing() {
return false;
}
#Override
public boolean shouldSelectCell(EventObject anEvent) {
return false;
}
#Override
public void removeCellEditorListener(CellEditorListener l) {
}
#Override
public boolean isCellEditable(EventObject anEvent) {
return true;
}
#Override
public Object getCellEditorValue() {
return list.getSelectedValuesList().toString();
}
#Override
public void cancelCellEditing() {
}
#Override
public void addCellEditorListener(CellEditorListener l) {
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
return list;
}
};
}
return super.getCellEditor(row, column);
}
};
Any suggestions?
I have solved my problem.
I have not been able to add multiple choice JComboBox, or a displayable JList on the Cell of the Jtable.
Instead, I have used a JOptionPane that displayed a JList.
Here's the code:
tableParametersFilter.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JTable target = (JTable)e.getSource();
int row = target.getSelectedRow();
int column = target.getSelectedColumn();
if(column == 2){
Parameter_Filter pf = view.listParameter_Filter.get(row);
if(pf instanceof Parameter_Filter_To_List_Of_Fields) {
Parameter_Filter_To_List_Of_Fields pftlof = (Parameter_Filter_To_List_Of_Fields) pf;
JList<String> jlist = new JList<String>(pftlof.list_of_fields_total_names);
String StringOfIntArray = (String) tableParametersFilter.getValueAt( row, 2);
int[] list_parameter_id = Statique.StringOfIntArrayToIntegerArray(StringOfIntArray);
if(list_parameter_id.length < jlist.getModel().getSize()) {
int[] list_places = pftlof.getPlaceOfParameters(list_parameter_id);
for(int i = 0; i < list_places.length; i++) {
jlist.setSelectedIndices(list_places);
}
}
JScrollPane scrollPane = new JScrollPane(jlist);
scrollPane.setPreferredSize( new Dimension( 500, 500 ) );
JOptionPane.showMessageDialog(
null, scrollPane, "Multi-Select Example", JOptionPane.PLAIN_MESSAGE);
int[] SelectedIndices = jlist.getSelectedIndices();
Integer[] listParametersId = new Integer[SelectedIndices.length];
for(int i = 0; i < SelectedIndices.length; i++) {
int id = pftlof.list_of_fields_Total[SelectedIndices[i]].id;
try {
Parameter p = Parameter.getParameter(
id,
Parameter_Filter_To_List_Of_Fields.getTotal_Parameter_In_Parameter_Filter_To_List_Of_Fields());
listParametersId[i] = p.id;
} catch (NoSuchFieldException e1) {
e1.printStackTrace();
}
}
System.out.println(Arrays.toString(listParametersId));
tableParametersFilter.setValueAt(Arrays.toString(listParametersId), row, 2);
}
}
}
}

I have a Jtable with a button in one of the columns and I want to access the value in the 1st column when I press the button

I Have a JTable with 3 columns: ID, Name and Operation. In this last column I have a button for every line ( I will post a printscreen ). When I press the button I want to access the value in the first column. I made a listener to the table and it works when I click on the table, but if I click in the button (that is in the 3rd column) it doesn't get the value ( I assume that it is because the click is not directly in the jtable).
How can I get the value when pressing the button?
Thank you
print screen of the JTable function
The listener I made:
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(final MouseEvent e) {
if (e.getClickCount() == 1) {
final JTable jTable= (JTable)e.getSource();
final int row = table.getSelectedRow();
final int column = table.getSelectedColumn();
final int valueInCell = (Integer)table.getValueAt(row, 0);
setSelectedID(valueInCell);
System.out.println("Selecionou: "+valueInCell);
}
}
});
Instead of adding regular JButtons to your table you could add your own custom JButton; which would implement ActionListener with the desired behavior when clicked (retrieve data), and at construction time would:
Receive (as an argument) and save the data that you want to reference in a field.
Registers itself as an ActionListener.
Such custom JButton would look like this:
public class DataButton<T> extends JButton implements ActionListener {
private T data;
public DataButton(T data) {
this.data = data;
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Selection: " + getData());
}
public T getData() {
return data;
}
}

TableView - Move up and Move down functionality of a cell

I have a situation where I have a TableView. I'm trying to implement a feature that allows a cell to be moved up or down. After moving the cell up or down (with the cell content), I want to change focus to the new location of the cell.
The problem is that it doesn't change to the new location. It for some reason stays in the original selected cell location.
This is the code used to move up, move down and change focus:
I am attempting to move a single selected cell.
public class TableController
{
private ObservableList<SimpleStringProperty> observablePrnPropertyData;
#FXML
private TableView<SimpleStringProperty> table;
#FXML
private TableColumn<SimpleStringProperty, String> data;
#FXML
private void initialize()
{
this.data.setCellValueFactory(cellData -> cellData.getValue());
this.data.setCellFactory(event -> new EditCell(this.observablePrnPropertyData, this.table));
}
public void display(final PrnProperty prnProperty)
{
this.observablePrnPropertyData = PrnPropertyUtil.getObservableDataFromPrnProperty(prnProperty);
this.table.setItems(this.observablePrnPropertyData);
}
private final class EditCell extends TableCell<SimpleStringProperty, String>
{
#Override
public void updateItem(String item, boolean empty)
{
super.updateItem(item, empty);
if (empty)
{
this.setText(null);
this.setGraphic(null);
}
else
{
this.setUpContextMenu();
this.setText(this.getString());
this.setGraphic(null);
}
}
private void setUpContextMenu()
{
// Context menu
ContextMenu contextMenu = new ContextMenu();
// context menu Move up
this.moveUp = new MenuItem("Move up");
this.moveUp.setOnAction(event -> this.moveUp(this.table, this.observablePrnPropertyData));
contextMenu.getItems().add(this.moveUp);
// Context menu for move down
this.moveDown = new MenuItem("Move down");
this.moveDown.setOnAction(event -> this.moveDown(this.table, this.observablePrnPropertyData));
contextMenu.getItems().add(this.moveDown);
// Add context menu
this.setContextMenu(contextMenu);
}
public void moveUp(final TableView<?> table, ObservableList listToManipulate)
{
final int selectedIndex = table.getSelectionModel().getSelectedIndex();
final Object removeItem = listToManipulate.remove(selectedIndex);
final int newIndex = selectedIndex - 1;
listToManipulate.add(newIndex, removeItem);
this.changeTableCellFocus(table, newIndex);
}
public void moveDown(final TableView<?> table, ObservableList listToManipulate)
{
final int selectedIndex = table.getSelectionModel().getSelectedIndex();
final Object remove = listToManipulate.remove(selectedIndex);
final int newIndex = selectedIndex + 1;
listToManipulate.add(newIndex, remove);
this.changeTableCellFocus(table, newIndex);
}
public void changeTableCellFocus(final TableView<?> table, final int focusIndex)
{
table.requestFocus();
table.getSelectionModel().clearAndSelect(focusIndex);
table.getFocusModel().focus(focusIndex);
}
}
}
It would be great if someone can give a working example. I really want to know what i'm doing wrong.
If you just have to focus next and previous line, you can try: table.getFocusModel().focusNext() and .focusPrevious(), like described here: http://docs.oracle.com/javafx/2/api/javafx/scene/control/FocusModel.html
For your case use this code will work fine, it is simple you must first get the selected index, move the item to the next (or previous) row, then select this new row.
void upClicked(){
if(table.getSelectionModel().getSelectedItem() != null) // check if the user really selected a row in the table
{
if(table.getSelectionModel().getSelectedIndex() != 0) // if the row first one so do nothing
{
int index = table.getSelectionModel().getSelectedIndex(); // get the selected row index
SimpleStringProperty x = table.getSelectionModel().getSelectedItem(); // get the selected item
table.getItems().set(index, table.getItems().get(index-1)); // move the selected item up
table.getItems().set(index-1, x); // change the row with the item in above
table.getSelectionModel().select(index-1); // select the new row position
}
}
}
void downClicked(){
if(table.getSelectionModel().getSelectedItem() != null)
{
if(table.getSelectionModel().getSelectedIndex() != table.getItems().size()-1) // if the row is in last so dont do nothing
{
int index = table.getSelectionModel().getSelectedIndex();
SimpleStringProperty x = table.getSelectionModel().getSelectedItem();
table.getItems().set(index, table.getItems().get(index+1));
table.getItems().set(index+1, x);
table.getSelectionModel().select(index+1);
}
}
}

How can I determine which cell in a JTable was selected?

I have a JTable in a GUI and I want to return a number based on the value of the cell that a user clicks on. This is the code:
ListSelectionModel newmodel = mytable.getSelectionModel();
newmodel.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int row = mytable.getSelectedRow();
int column = mytable.getSelectedColumn();
int cell = getNewNum();
datefield.setText(String.valueOf(cell));
}
});
I have a couple of problems with this. Firstly this method makes my table editable. Before I used this method I couldn't edit the table but now I can delete entries. I looked in the API but I don't know why this is. Secondly, if I click on a cell in row 3, say, and then I click on another row in cell 3, no event is registered. How can I make an event from clicking in a cell on the currently selected row?
A common method is to get the point where the user clicked through the event:
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
int row = jTable1.rowAtPoint(evt.getPoint());
int col = jTable1.columnAtPoint(evt.getPoint());
if (row >= 0 && col >= 0) {
......
}
}
});
Here is a second option using selection mode:
jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
...
int row = jTable1.getSelectedRow();
int col = jTable1.getSelectedColumn());
if (evt.getClickCount() > 1) { // double-click etc...
...
If you go:
public boolean isCellEditable(int row, int col) {
return false;
}
Then your JTable will not be editable.
Finally in order to get the value you want, you just need to call the getValueAt(row,col) of your JTable Model, or get the contents like this:
Object foo = jTable1.getModel().getValueAt(row, col);

How can I put a "(de)select all" check box in an SWT Table header?

I have an SWT Table that I'm instantiating with the SWT.CHECK style in order to display a check box next to every row. My users have requested another check box in the header row of the table in order to allow them to select/deselect all the rows with one click.
I can't see any obvious way to do it, and I've only found Swing/JTable examples through Google. Does anyone know how to do this? I'm hoping it's possible without re-implementing Table or falling back on a header context menu.
Just create two images of check box. First one without a tick and second one having a tick.Now add the first image to the tableColumn header. After that add listener to tableColumn in such a way that when you click button for the first time, table.selectALL() method should be fired along with changing the tableColumn header image to second one. When you click button again call table.deSelectAll() method and replace the tableColumn header with the first image.
You can use this condition:
When the checkbox(image) is clicked, use a for loop to check whether,
any of the checkboxes in the table is checked. if anyone is found
checked then fire table.deSelectAll() method , else fire
table.selectAll() method.
There will not be any problem for the "checkbox" during table/widow resizing.
tableColumn0.addListener(SWT.Selection, new Listener() {
#Override
public void handleEvent(Event event) {
// TODO Auto-generated method stub
boolean checkBoxFlag = false;
for (int i = 0; i < table.getItemCount(); i++) {
if (table.getItems()[i].getChecked()) {
checkBoxFlag = true;
}
}
if (checkBoxFlag) {
for (int m = 0; m < table.getItemCount(); m++) {
table.getItems()[m].setChecked(false);
tableColumn0.setImage(new Image(Display.getCurrent(),
"images/chkBox.PNG"));
table.deselectAll();
}
} else {
for (int m = 0; m < table.getItemCount(); m++) {
table.getItems()[m].setChecked(true);
tableColumn0.setImage(new Image(Display.getCurrent(),
"images/chkBox2.PNG"));
table.selectAll();
}
}
}
});
You could use a FormLayout to allow stacking objects, then add a checkbox on top of the table as follows:
FormData fd = new FormData();
fd.left = new FormAttachment(table, 5, SWT.LEFT);
fd.top = new FormAttachment(table, 5, SWT.TOP);
checkbox.setLayoutData(fd);
checkbox.moveAbove(table);
You might find it useful for correctly aligning the checkbox to obtain the height of the table header row with table.getHeaderHeight().
Fully describe this code :: de)select all” check box in an SWT Table
header
public class TaskView extends ViewPart {
public static TableItem std_item;
public static List<Student> std=new ArrayList<Student>();
public static Table table;
private TableColumn col_name_add;
private TableColumn col_image_add;
static int countcheck;
static int staticno=1;
static int check=0,uncheck=0;
public TaskView() {
setTitleImage(ResourceManager.getPluginImage("RCP_Demo", "icons/Tasksview.png"));
}
#Override
public void createPartControl(Composite parent) {
parent.setLayout(null);
////////// Table Create
table = new Table(parent, SWT.BORDER | SWT.FULL_SELECTION|SWT.CHECK|SWT.CENTER);
////SWT.CHECK: Display first column check box
table.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
TableItem item = table.getItem(table.getSelectionIndex());
for(int col=1;col<table.getColumnCount();col++)
{
//Table_Column Checked or Not
if(item.getChecked())
item.setChecked(false);
else
item.setChecked(true);
/////////First column value get
if(col==1)
{
System.out.println(item.getText(col));
}
TableItem[] itemCheck = table.getItems();
for(int i=0;i<table.getItemCount();i++)
{
if(itemCheck[i].getChecked())
++check;
else
++uncheck;
}
if(check==table.getItemCount())
//Change column image:Checkbox checked
col_image_add.setImage(ResourceManager.getPluginImage("RCP_Demo", "icons/check.png"));
else
//Change column image:Checkbox Unchecked
col_image_add.setImage(ResourceManager.getPluginImage("RCP_Demo", "icons/uncheck.png"));
//System.out.println("Check:"+check+"uncheck"+uncheck);
check=0;
uncheck=0;
}
}
});
table.setBounds(10, 10, 343, 297);
table.setHeaderVisible(true);
table.setLinesVisible(true);
////// SWT Table header Column
col_image_add = new TableColumn(table, SWT.LEFT);
col_image_add.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
//All Row selected or Not
//column Icon change checked(selected) or not
System.out.println("Total Row Count:"+table.getItemCount());
TableItem item[] = table.getItems();
if(staticno==1)
{
for(int i=0;i<table.getItemCount();i++)
{
item[i].setChecked(true);
col_image_add.setImage(ResourceManager.getPluginImage("RCP_Demo", "icons/check.png"));
}
staticno=0;
}else
{
for(int i=0;i<table.getItemCount();i++)
{
item[i].setChecked(false);
col_image_add.setImage(ResourceManager.getPluginImage("RCP_Demo", "icons/uncheck.png"));
}
staticno=1;
}
}
}
});
col_image_add.setMoveable(true);
col_image_add.setToolTipText("Click");
col_image_add.setImage(ResourceManager.getPluginImage("RCP_Demo", "icons/uncheck.png"));
col_image_add.setWidth(36);
//Dynamic column Name add
String[] Col_names={"Stud_id","Stud_Name","Stud_Gender"};
for(int i=0;i<Col_names.length;i++)
{
col_name_add = new TableColumn(table,SWT.CENTER);
col_name_add.setWidth(100);
col_name_add.setText(Col_names[i]);
}
}
public TableViewer getViewer() {
return null;
}
}
thanks....

Categories