Get selected cell value in JTable [duplicate] - java

This question already has answers here:
How to get cell value of jtable depending on which row is clicked
(2 answers)
Closed 7 years ago.
When I double click the cell of the JTable, I want it to take the value of that cell and write it in the textfield. What should I do? Here is what I have tried so far, but I don't know where to go from here:
table_1.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JTable table = (JTable) me.getSource();
Point p = me.getPoint();
int row = table.rowAtPoint(p);
if (me.getClickCount() == 2) {
textfield.settext(???????????);
}
}
});
i understand how it works:
int row = table.rowAtPoint(p);
int column = table.columnAtPoint(p);
textfield.settext(table_1.getValueAt(row, column));

Jtable table = (JTable)e.getsource();
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
ObjectType o = (ObjectType)target.getValueAt(row, column) );
Do this. Will get the value in your JTable based on the row and column selected and then casts the returned value to your object type in the table and returns the value at the row, column. This is inside your Listener.
Shown in similar question Possible Dup?

You can get the value of the table by using:
table.getModel().getValueAt(row, col);
where
row - the row whose value is to be queried
col - the column whose value is to be queried
table - your object name (class jTable)
Note: The column is specified in the table view's display order, and not in the TableModel's column order. This is an important
distinction because as the user rearranges the columns in the table,
the column at a given index in the view will change. Meanwhile the
user's actions never affect the model's column ordering.
In addition, I recommend to read this documentation.

Try to write something like this:
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(final MouseEvent e) {
if (e.getClickCount() == 1) {
final JTable jTable= (JTable)e.getSource();
final int row = jTable.getSelectedRow();
final int column = jTable.getSelectedColumn();
final String valueInCell = (String)jTable.getValueAt(row, column);
textfield.setText(valueInCell);
}
});

Related

Updating checkboxes in Jtable goes into recursion, causes stack overflow error

I have a Jtable set up in a tabbed pane that is filled with an id and checkboxes. The table looks something along the lines of this, where . are the checkboxes.
| VAR1 |
ID | ALL | subVar1 | subVar2 |
------------------------------
id1| . | . | . |
Now, I also have a TableListener attached to this table. What I would like to happen is that, whenever a user presses the ALL checkbox, all the checkboxes in that row need to be selected (ie true). This is the table listener code.
#Override
public void tableChanged(TableModelEvent e) {
if(e.getSource() == assignedTableModel) {
for (int i = 0; i < aTable.getRowCount(); i++) {
boolean isAllChecked = (Boolean) aTable.getValueAt(i, 1);
if(isAllChecked) {
assignedTableModel.setValueAt(Boolean.TRUE, i, j);
}
else {
...
}
}
}
}
Clicking the ALL checkbox causing the table to change, assignedTableModel.setValueAt(Boolean.TRUE, i, j); is called, the table is changed again and therefore calls the listener, which calls this function again.
My question, is there another way of updating the checkboxes? Or is there a way to set a base to get out of the recursion?
EDIT The rows are added dynamically. I'm wondering if adding an actionListener to the ALL checkbox as it's being added will be a solution. I'll come back with how it turns out.
EDIT2 I'd forgot to mention that the whole table is generated dynamically. That means I have no way of knowing how many columns and rows will be present, the only columns I know are ID and the ALL col. Most answers already present deal with hard coded implementations.
whenever a user presses the ALL checkbox, all the checkboxes in that row are selected
So why are you looping through all the rows in your code? The event will be generated only for the row you click and you only need to select the check marks for the columns on that row. Get rid of the looping code.
the table is changed again and therefore calls the listener, which calls this function again.
You need an if condition to identify when the check box in the first column is checked:
if (e.getType() == TableModelEvent.UPDATE)
{
int row = e.getFirstRow();
int column = e.getColumn();
if (column == 0)
{
TableModel model = (TableModel)e.getSource();
model.setValueAt(Boolean.true, row, 1);
...
}
}
Now the change of state on the other columns will be ignored.
Based off of #camickr's response, the following piece of code seems to be doing the trick. Thanks.
#Override
public void tableChanged(TableModelEvent e) {
if (e.getType() == TableModelEvent.UPDATE && e.getSource() == assignedTableModel)
{
int row = e.getFirstRow();
int column = e.getColumn();
if (column == 1)
{
DefaultTableModel model = (DefaultTableModel) e.getSource();
for(int i=2 ; i<model.getColumnCount() ; i++) {
if((boolean) model.getValueAt(row, 1))
model.setValueAt(Boolean.TRUE, row, i);
else
model.setValueAt(Boolean.FALSE, row, i);
}
}
}
}

how do I determine which columns in a JTable are visible

I'm resizing my columns according to their data with the following:
/**
* Set the widths of the columns in the table according to the data in the table.
* #param table
*/
private static void setColumnWidths(JTable table)
{
int columnCount = table.getModel().getColumnCount();
int rowCount = table.getModel().getRowCount();
TableColumnModel columnModel = table.getColumnModel();
for (int col=0; col<columnCount; col++)
{
TableColumn column = columnModel.getColumn(col);
TableCellRenderer renderer = column.getCellRenderer();
if (renderer == null)
{
renderer = new DefaultTableCellRenderer();
}
int overallColumnWidth = 0;
for (int row = 0; row < rowCount; row++)
{
Object value = table.getValueAt(row, col);
Component component = renderer.getTableCellRendererComponent(table, value, false, false, row, col);
int componentWidth = (int) component.getPreferredSize().getWidth();
overallColumnWidth = Math.max(componentWidth, overallColumnWidth);
}
column.setPreferredWidth(overallColumnWidth);
}
}
This works when all the columns are visible, but I've got code that hides some of them (JTable.removeColumn(TableColumn column)). It appears that both the JTable instance and the TableColumnModel instance have the list of data columns, i.e., all columns regardless of visibility. How can I get a list of only columns that are visible, or test whether a given column is visible?
(I've searched for this, but get longs lists of articles on how to hide the columns, and no explanation of where the visible/invisible information is kept. I thought, since I asked the JTable to hide the column, that somewhere in there it would know which columns were hidden and I could get that info.)
Check if table.convertColumnIndexToView(col) returns -1.
From the documentation:
public int convertColumnIndexToView(int modelColumnIndex)
Maps the index of the column in the table model at modelColumnIndex to
the index of the column in the view. Returns the index of the
corresponding column in the view; returns -1 if this column is not
being displayed. If modelColumnIndex is less than zero, returns
modelColumnIndex.
Source
The problem with your code if that your loops is controlled by the values returned in the TableMdoel.
Instead you should be using values from the table:
int rowCount = table.getRowCount();
int columnCount = table.getRowCount();
Then there is no need for exception logic to determine if a column is visible or not because by default it will be visible because it is the job of the view (JTable) to only display visible columns.
You need to understand the difference between the "view" and the "model".
how do I determine which columns in a JTable are visible
So the better answer is to use the methods of the JTable. Your current solution confuses the view and model.
You could also use the Table Column Adjuster to do the column adjustment for you. It provides features like dynamically resizing the column as the data changes.

JTable cell updating issue

I got a problem I can't resolve alone and with help of other topics there. Found some 1 pretty similar but it hasn't help.
My problem is kind of tricky ones I think, I'll try to explain this as good as I can.
So, I got a JTable with couple of columns, column 2 and 3 are editable and column 4 is a product of these two (col4 = col2*col3). What I am going to do is when I edit column 2 or 3, column 4 will automaticly update it's value. I acomplished that but not fully.
The cell is updating only when I finish editing by mouseclick. I'd like to cell react with same way if editing is finished by ENTER key.
I was trying a little bit with:
if(recipeTable.getCellEditor()!=null)recipeTable.getCellEditor().stopCellEditing();
but it isn't changing anything.
Here is my code:
recipeTableModel = new DefaultTableModel(COLUMN_HEADLINE, 0) {
#Override
public boolean isCellEditable(int row, int column)
{
model.updateTotalPriceInTable(recipeTable);
return (column == 2) || (column == 3);
}
};
And:
public void updateTotalPriceInTable(JTable table)
{
double totalPrice;
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
for(int i = 0; i < tableModel.getRowCount(); i++)
{
totalPrice = Double.parseDouble(tableModel.getValueAt(i, 2).toString()) * Double.parseDouble(tableModel.getValueAt(i, 3).toString());
tableModel.setValueAt(totalPrice, i, 4);
}
tableModel.fireTableDataChanged();
}
~~~~~~~~~~~~~~~~~~~~~~~~
Ok I figured it out, that is code the code that resolved my problem:
#Override
public void setValueAt(Object aValue, int row, int column)
{
Vector rowVector = (Vector)dataVector.elementAt(row);
rowVector.setElementAt(aValue, column);
rowVector.setElementAt(Double.parseDouble((String) rowVector.get(2))*Double.parseDouble((String) rowVector.get(3)), 4);
fireTableDataChanged();
}
Override the setValueAt(...) method of your TableModel. You invoke super.setValueAt(...) to save the data normally.
Then whenever the data in column 2 or 3 changes, you then calculate the value of column 4 and update the model.

How to use hidden column data of jTable in tooltip

I am trying to display the data of hidden column as tooltip. Hiding is working perfectly using the following code:
JTable table = new JTable(model){
//Implement table cell tool tips.
public String getToolTipText(MouseEvent e) {
String tip = null;
java.awt.Point p = e.getPoint();
int rowIndex = rowAtPoint(p);
int colIndex = columnAtPoint(p);
int realColumnIndex = convertColumnIndexToModel(colIndex);
try {
tip = getValueAt(rowIndex, 8).toString();
} catch (RuntimeException e1) {
//catch null pointer exception if mouse is over an empty line
}
return tip;
}
};
TableColumnModel tcm = table.getColumnModel();
TableColumn tc;
for(int i = 1; i <= 7; i++){
tc = tcm.getColumn(8);
tcm.removeColumn(tc);
}
But the tooltip is not showing the data of hidden column (getValue function is not returning value). So do hiding the column delete the data as well ?
You do not need to for loop as you do not use the i variable ;-)
The removeColumn on the JTable does not remove the data from the model, as clearly stated in the javadoc
Removes aColumn from this JTable's array of columns. Note: this method does not remove the column of data from the model; it just removes the TableColumn that was responsible for displaying it.
There is no mention in the javadoc for the same method on the TableColumnModel, but I would assume it works the same way, but you can always give it a try to call it on the JTable instead
The real problem in your code is the use of getValueAt, which uses the row and column index of the table, and not of the model
Note: The column is specified in the table view's display order, and not in the TableModel's column order. This is an important distinction because as the user rearranges the columns in the table, the column at a given index in the view will change. Meanwhile the user's actions never affect the model's column ordering.
And since you removed that column, it simply does not exists for the table. Call the getValue method on the model instead, and do not forget to convert the row index

How to add tooltips to JTable's rows

how can I add tooltips to JTable's rows (Java Swing)?
These tooltips should contain same values of the relative row.
This is the code I used in my class that extends JTable. It overrides the method "prepareRenderer", but I got empty cells, and it adds a tooltip for each single cell within row, not one tooltip for the whole row (that is what I'm looking for):
public Component prepareRenderer(TableCellRenderer renderer,int row, int col) {
Component comp = super.prepareRenderer(renderer, row, col);
JComponent jcomp = (JComponent)comp;
if (comp == jcomp) {
jcomp.setToolTipText((String)getValueAt(row, col));
}
return comp;
}
it adds a tooltip for each single cell within row, not one tooltip for the whole row
You are changing the tooltip depending on the row and column. If you only want the tooltip to change by row, then I would only check the row value and forget about the column value.
Another way to set the tooltip is to override the getToolTipText(MouseEvent) method of JTable. Then you can use the rowAtPoint(...) method of the table to get the row and then return the appropriate tool tip for the row.
Just use below code while creation of JTable object.
JTable auditTable = new JTable(){
//Implement table cell tool tips.
public String getToolTipText(MouseEvent e) {
String tip = null;
java.awt.Point p = e.getPoint();
int rowIndex = rowAtPoint(p);
int colIndex = columnAtPoint(p);
try {
//comment row, exclude heading
if(rowIndex != 0){
tip = getValueAt(rowIndex, colIndex).toString();
}
} catch (RuntimeException e1) {
//catch null pointer exception if mouse is over an empty line
}
return tip;
}
};
see JComponent.setToolTipText() -- the JComponent you want on per-row data is not the table, but rather the cell renderer of the data, which has access to configuring a JComponent for each rendered cell.
rowIndex can be ZERO.
change:
if(rowIndex != 0){
tip = getValueAt(rowIndex, colIndex).toString();
}
by:
if(rowIndex >= 0){
tip = getValueAt(rowIndex, colIndex).toString();
}

Categories

Resources