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

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);

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);
}
}
}
}

Adding button to the GXT Grid cell

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;
}
});

How to disable a specific cell with JPopupmenu's JMenuItem?

I have created a simple JTable and wish to be able to disable a cell after right clicking it and selecting the option in the JPopupMenu with a JMenuItem that will disable the selected cell, here's my MouseAdapter:
private JPopupMenu popup;
private JMenuItem one;
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
int r = table.rowAtPoint(e.getPoint());
if (r >= 0 && r < table.getRowCount()) {
table.setRowSelectionInterval(r, r);
} else {
table.clearSelection();
}
int rowindex = table.getSelectedRow();
if (rowindex < 0)
return;
if (e.isPopupTrigger() && e.getComponent() instanceof JTable) {
int rowIndex = table.rowAtPoint(e.getPoint());
int colIndex = table.columnAtPoint(e.getPoint());
one = new JMenuItem("Disable this cell");
popup = new JPopupMenu();
popup.add(one);
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
});
Now, I know you can disable particular cell(s) by doing:
DefaultTableModel tab = new DefaultTableModel(data, columnNames) {
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
but this is disabling the cell on creation of JTable but I need to disable the cell after creation. Any ideas/leads on how this can be done?
You'll need to modify your TableModel to add storage for the desired editable state of each cell, e.g. List<Boolean>. Your model can return the stored state from isCellEditable(), and your mouse handler can set the desired state in your TableModel. You may need the model/view conversion methods mentioned here.

Adding actionlistener of column in a jtable

Hi everyone..
I need some help again. :)
How to do this? When I click the column t1, another form must pop-up explaining what happens to column t1, say, at time 1, Instruction 1 is in fetch stage. Then, when I click naman t2 column, Instruction 2 is in fetch stage and Instruction 1 is in Decode stage., so on and so forth.
Thank you in advance. I really need your help..
Regards.. :)
You need to add following chunk of code,
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// This is for double click event on anywhere on JTable
if (e.getClickCount() == 2) {
JTable target = (JTable) e.getSource();
int row = target.getSelectedRow();
int column = target.getSelectedColumn();
// you can play more here to get that cell value and all
new DialogYouWantToOpen(row, Column);
}
}
});
A Dialog which will be opened on double click.
class DialogYouWantToOpen extends JDialog{
JLabel testLabel = new JLable();
public DialogYouWantToOpen(int row, int column){
setSize(200,200)
setLayout(new FlowLayout());
testLabel.setText("User double clicked at row "+row+" and column "+ column);
add(testLabel);
}
}
Generaly it should go something like this
Listener listener = new Listener() {
public void handleEvent(Event e) {
TableColumn column = (TableColumn) e.widget;
System.out.println(column);
}
};
you get the column out of event and then do what you want with it.

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