make only one checkbox selectable in JTable Column - java

I have a JTable with 2 coloumns, one column is object type, second column is checkbox. In that table user want to select only a single checkbox. I am tried many codes (Examples : jtable checkbox single selection and Second one), finally i done this by using function.
Here is my function:
public void setSelectionEnableOrDisable(JTable table) {
int earlierSelectionRow = 0;
int selectedRow = table.getSelectedRow();
for (int i = 0; i < table.getRowCount(); i++) {
if ((Boolean) table.getValueAt(i, 1) == true && i != selectedRow) {
earlierSelectionRow = i;
}
}
table.setValueAt(true, selectedRow, 1);
table.setValueAt(true, earlierSelectionRow, 1);
}
But, whats the problem with this one is, when i clicking the checbox slowly it's fine. if i am clicking fastly 2 or 3 checkboxes then my code allows to multi selection. What's wrong here?.

I think you can do it simpler, like:
public void setSelectionEnableOrDisable(JTable table) {
int selectedRow = table.getSelectedRow();
if ((Boolean)table.getValueAt(selectedRow , 1)) {
for (int i = 0; i < table.getRowCount(); i++) {
if ( i != selectedRow) {
table.setValueAt(false, i, 1);
}
}
}

Related

How do I get table information in word2003 using POI?

I try to get the width of each cell and then calculate their greatest common divisor to get the colspan of each cell, but how do I get the cell Rowspan? I tried using the method TableRow.getRowHeight(), but no matter what the table looks like, it's always going to be 0.
I am trying to use this method to convert to HTML, if you have a better way to convert complex tables to HTML, please help me, thanks!
public static Integer getRowspan(TableCell cell, int rowNum, int colNum, Table table) {
int rowSpan = 0;
if (cell.isVerticallyMerged()) {
if (cell.isFirstVerticallyMerged()) {
for (int i = rowNum + 1; i < table.numRows(); i++) {
TableCell tableCell = table.getRow(i).getCell(colNum);
if (tableCell.isFirstVerticallyMerged() || !tableCell.isVerticallyMerged()) {
rowSpan = i - rowNum;
break;
} else if (i == table.numRows() - 1) {
rowSpan = i - rowNum + 1;
}
}
}
}
return rowSpan;
}
public static Integer getColspan(TableCell cell, int rowNum, int colNum, Table table) {
int colSpan = 0;
if (cell.isMerged()) {
if (cell.isFirstMerged()) {
for (int i = colNum + 1; i < table.numRows(); i++) {
TableCell tableCell = table.getRow(rowNum).getCell(i);
if (tableCell.isFirstMerged() || !tableCell.isMerged()) {
colSpan = i - colNum;
break;
} else if (i == table.numRows() - 1) {
colSpan = i - colNum + 1;
}
}
}
}
return colSpan;
}

SWT Snippet2. Table sorting. items array changes in the loop. How does this work?

http://git.eclipse.org/c/platform/eclipse.platform.swt.git/tree/examples/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet2.java
I am trying in SWT to add sorting to a table widget. Copying the code from Snippet2 sortListener Handler doesn't work. It correctly swaps two items into sorted order. More than 2 items in the table, and the results are unpredictable.
It seems to me (in the following code extract from Snippet2 sortListener) that items[i].dispose() is going to change the array of TableItems called items that we are iterating over in the outer for loop, for (int i = 1 ...... Also, when one item is disposed(), and inserted into items at a new index, the whole array is recreated afresh. That surely breaks the iteration?
So, I guess I have two questions:
What am I not understanding about Snippet2's algorithm?
Is there any other obvious reason why a sort operation might return random results (bearing in mind I am a noob, so am likely to have made the stupidest of mistakes)?
Here is my code:
Listener sortListener = new Listener() {
public void handleEvent(Event e) {
TableItem[] items = table.getItems();
Collator collator = Collator.getInstance(Locale.getDefault());
TableColumn column = (TableColumn)e.widget;
int index = column == column1 ? 0 : 1;
for (int i = 1; i < items.length; i++) { <--------- HERE
String value1 = items[i].getText(index);
for (int j = 0; j < i; j++){
String value2 = items[j].getText(index);
if (collator.compare(value1, value2) < 0) {
String[] values = {items[i].getText(0), items[i].getText(1)};
items[i].dispose(); <--------- HERE
TableItem item = new TableItem(table, SWT.NONE, j);
item.setText(values);
items = table.getItems(); <--------- HERE
break;
}
}
}
table.setSortColumn(column);
}
};
This code snippet works for any number of items in the table (I tested it).
But it works only for 2 columns. (Is that your problem?)
If you have more columns in the table, the code would look like this:
Listener sortListener = new Listener() {
public void handleEvent(Event e) {
TableItem[] items = table.getItems();
Collator collator = Collator.getInstance(Locale.getDefault());
TableColumn column = (TableColumn)e.widget;
int index = table.indexOf(column);
for (int i = 1; i < items.length; i++) { // <--------- HERE
String value1 = items[i].getText(index);
for (int j = 0; j < i; j++){
String value2 = items[j].getText(index);
if (collator.compare(value1, value2) < 0) {
String[] values = new String[table.getColumnCount()];
for (int columnIdx = 0; columnIdx < table.getColumnCount();
columnIdx++){
values[columnIdx] = items[i].getText(columnIdx);
}
items[i].dispose(); // <--------- HERE
TableItem item = new TableItem(table, SWT.NONE, j);
item.setText(values);
items = table.getItems(); // <--------- HERE
break;
}
}
}
table.setSortColumn(column);
}
};
You may want to use JFace wrapper for SWT table (org.eclipse.jface.viewers.TableViewer), which gives your table more built in features. I suggest this tutorial for JFace TableViewer. Here is tutorial for sorting TableViewer.

Java Getting JTable Value (Per row)

I would like to get the value from the Jtable, and I tried it using the getvalueat however whenever I try to get the value from the JTable it only get the value from the first column of the selected row, I need to get all the value from the Jtable which I selected. Can you please help me with this one
here is my code:
class GetTableValue implements ActionListener{
public void actionPerformed(ActionEvent e){
AbstractButton button = (AbstractButton)e.getSource();
if(e.getActionCommand().equals(button.getActionCommand)){
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
Object data = (Object)table.getValueAt(row, col);
JOptionPane.showMessageDialog(null, data);
}
}
}
This is my action event where the value of the selected table is shown in the JOptionPane unfortunately it only display one value(which is the one you already selected) not the whole row.
This code is for my Jbutton for call the action event(I already excluded my code from the JTable since it fetch the Jtable value from my database)
ActionListener tableAction = new GetTableValue();
buttonEdit = new JButton("EDIT");
buttonEdit.addActionListener(tableAction);
the code is plain and simple, I also search Mr. G(google) about a good tutorial on fetching row, unfortunately there isn't a good tutorial for fetching Jtable value(per row).
If you want all the values from selected row then try this code.
int row = jTable1.getSelectedRow();
int column = jTable1.getColumnCount();
for(int i = 0; i < column; i++) {
System.out.println(jTable1.getValueAt(row, i));
}
You get the all values for selected row, no matter how much columns are there in jtable
If you want all the values from jtable then try:
int row = jTable1.getRowCount();
int column = jTable1.getColumnCount();
for (int j = 0; j < row; j++) {
for (int i = 0; i < column; i++) {
System.out.println(jTable1.getValueAt(j, i));
}
}
Yes you can use Object[] to store the values. For example:
Object[] val = new Object[column];
for (int k = 0; k < val.length - 1; k++) {
for (int j = 0; j < row; j++) {
for (int i = 0; i < column; i++) {
val[k] = jTable1.getValueAt(j, i);
System.out.println(val[k]);
}
}
}
getValueAt will return you the value of the cell (at row/col). Unless you're table model supports it, there is no convenient way (beyond what you are doing) to get the whole row in a single request.
Also, remember, if the table is sorted or filtered, the model indices will not match the view, you need to convert them first, using convertRowIndexToModel and convertColumnIndexToModel
UPDATE
The only way around it is if the table model you're using has a getRow (or equivalent) method. Without know how you are storing the data in the table model it's next to near impossible to give an accurate answer, but a general idea would be...
public class MyAwesomeTableModel extends AbstractTableModel {
// All the usual stuff...
public MyRowData getRowAt(int index) { ... }
}
Now, MyRowData is what ever implementation of the table data you've created. It could be (preferably) a single Object or in the case of the DefaultTableModel an array of objects.
class GetTableValue implements ActionListener{
public void actionPerformed(ActionEvent e){
AbstractButton button = (AbstractButton)e.getSource();
if(e.getActionCommand().equals(button.getActionCommand)){
int row = table.convertRowIndexToModel(table.getSelectedRow());
MyAwesomeTableModel model = (MyAwesomeTableModel)table.getModel();
MyRowData data = model.getRowAt(row);
JOptionPane.showMessageDialog(null, data);
}
}
}
This is all dependent on how you've implemented your TableModel and how you've implemented your row data, but that's the general jist
private void jTable1MousePressed(java.awt.event.MouseEvent evt) {
int selectedRow;
ListSelectionModel rowSM = jTable1.getSelectionModel();
rowSM.addListSelectionListener(new ListSelectionListener()
{
#Override
public void valueChanged(ListSelectionEvent e)
{
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
selectedRow = lsm.getMinSelectionIndex();
int numCols = jTable1.getColumnCount();
model = (DefaultTableModel) jTable1.getModel();
System.out.print(" \n row " + selectedRow + ":");
for (int j = 0; j < numCols; j++)
{
System.out.print(" " + model.getValueAt(selectedRow, j));
}
}
});
}
Using this you can get value of whole row where u click on particular row.
you can try the below code to get selected row value:
int selectedRow = jTableName.getSelectedRow();
selectedRow = jTableName.convertRowIndexToModel(selectedRow);
String val1 = (String)jTableName.getModel().getValueAt(selectedRow, 0);
String val2 = (String)jTableName.getModel().getValueAt(selectedRow, 1);

Why does JTable always trigger ListSelectionListener twice?

Is it normal that any changes to the selected row of the JTable will trigger the added ListSelectionListener twice?
Is it possible that the ListSelectionListener can be triggered only once?
Look at the event that is passed to your listener, specifically
ListSelectionEvent.getValueIsAdjusting()
perform whatever ops you want to do when this returns false.
ListSelectionEvent.getValueIsAdjusting() will work as commented by #MeBigFatGuy.
Similar example:
if(!e.getValueIsAdjusting()){
String selectedData = null;
int selectedRow = table.getSelectedRow();
int selectedColumns = table.getSelectedColumn();
for (int i = 0; i <= selectedRow; i++) {
for (int j = 0; j <= selectedColumns; j++) {
selectedData = (String) table.getValueAt(selectedRow, selectedColumns);
}
}
System.out.println("Selected: " + selectedData);
}
it'll be triggered just once.

searchings rows from table

i want to select particular rows from the JTable which contains a particular string.. please help me for this..
Something like this will do the trick:
void selectMatchingRows(JTable table, String regex)
{
for (int row = 0; row < table.getModel().getRowCount(); row++)
{
for (int col = 0; col < table.getModel().getColumnCount(); col++)
{
if (table.getModel().getValueAt(row, col).toString().matches(regex))
{
table.getSelectionModel().setSelectionInterval(row, row);
}
}
}
}
Making sure the ListSelectionModel.selectionMode is MULTIPLE_INTERVAL_SELECTION.
Call JTable.getModel then just loop through using TableModel.getValueAt

Categories