Get Sum of a Specific Column on Editing a Cell in Jtable - java

I am trying to get the sum of column 4 on typing/editing the value on column 4. Immediately i change the figure i.e as i type on any row of column 4 it should change my sum which i set on a jTextField.
I have tried TableModelListener and ListSelectionListener but it has not worked efficiently because i have to click on the row for it to get the summary.
jTable1.getModel().addTableModelListener(new TableModelListener(){
public void tableChanged(TableModelEvent evt){
float sum = 0;
int[] rows = jTable1.getSelectedRows();
for(int i=0;i<jTable1.getRowCount();i++){
try{
sum = sum +
Float.parseFloat(jTable1.getValueAt(rows[i],4).toString());
}
catch(Exception e){
continue;
}
}
jTextField15.setText(Float.toString(sum));
getsummaries();
}
});
Immediately i change the value on Column 4 i would like it ot autosum on jTextField15.

it has not worked efficiently because i have to click on the row for it to get the summary.
The model is only updated when the cell loses focus because that is when the value you are typing is saved to the model. This is because you could start typing numbers and then use the "escape" key to cancel the editing.
If you really want to update the total as the user types into the editor, then instead of using a TableModelListener, you will need to add a DocumentListener to the text field used by the editor:
DefaultCellEditor editor = (DefaultCellEditor)table.getDefaultEditor(Integer.class);
JTextField textField = (JTextField)editor.getComponent();
textField.getDocument().addDocumentListener(...);
See the section from the Swing tutorial on Listening For Changes on a Document for more information and examples.
Of course if you do this, you will also need to handle the case when the editor is cancelled. So you will also need to add a PropertyChangeListener to the JTable and listen for tableCellEditor property change.

I have not yet gotten a solution to this yet. On typing on JTable it's difficult to record the sum. A workaround would be to create a button and it computes the total on the jTextField.

Related

Cell dropdown does not work when hiding row numbers

I have a Nattable that can hide his row numbers. now when I hide the row numbers it does not show the dropdown in a cell.
I use this code to hide the row numbers:
if (showRowNumbers) {
compositeGridLayer = new GridLayer(bodyLayer, finalHeaderRow, rowHeaderLayer, cornerLayer);
} else {
compositeGridLayer = new CompositeLayer(1, 2);
compositeGridLayer.setChildLayer(GridRegion.COLUMN_HEADER, columnHeaderLayer, 0, 0);
compositeGridLayer.setChildLayer(GridRegion.BODY, bodyLayer, 0, 1);
compositeGridLayer.setChildLayer(GridRegion.COLUMN_HEADER, finalHeaderRow, 0, 0);
}
For adding the drop down to the cell we register it using:
ComboBoxCellEditor comboBoxCellEditor = new ComboBoxCellEditor(phases, -1);
comboBoxCellEditor.setMultiselect(false);
comboBoxCellEditor.setUseCheckbox(false);
comboBoxCellEditor.setFreeEdit(false);
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER, new ComboBoxPainter(),
DisplayMode.NORMAL, "phaseDropDown");
comboBoxCellEditor.setIconImage(GUIHelper.getImage("plus"));
configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, comboBoxCellEditor, DisplayMode.EDIT,
"phaseDropDown");
configRegistry.registerConfigAttribute(CellConfigAttributes.DISPLAY_CONVERTER, new DefaultDisplayConverter() {
#Override
public Object canonicalToDisplayValue(Object canonicalValue) {
return super.canonicalToDisplayValue(canonicalValue);
}
}, DisplayMode.NORMAL, "phaseDropDown");
How can I hide the row numbers without removing the drop down in the table?
Not sure what you mean with "hiding row numbers". Hiding would imply that you want to do this dynamically. And the approach you are showing would not be dynamically.
If you mean you want to provide two different compositions, one with row numbers and one without, the approach would be correct. You use a different composition. What I don't understand is why you set a column header twice with different layers.
The next question, what do you mean with "does not show the dropdown"? Don't you see the small triangle or does the combobox not open? I guess you mean the combobox does not open on click. I suppose the reason is that you forgot to register the necessary editing configurations on the newly created CompositeLayer. The GridLayer is created with the default configuration. On the CompositeLayer you do not set any configuration. So actually even print, export and alternate row colors will not work as they are simply not configured.
You need to register the DefaultEditConfiguration and the DefaultEditBindings on the CompositeLayer. This is explained in our NatTable Documentation|Editing. And I'm sure we also have some examples that cover editing in a non-grid composition.

How to get the currently selected cell's indices in JTable immediately after it is highlighted?

I'm building a spread sheet application. But this is not a question like using table.getSelectedColumn() and table.getSelectedRow() to find the selected cell in a JTable.
In Microsoft Excel, when we navigate through cells using arrow keys, the content in the cells are displayed in the Formula Bar immediately after highlighting the cell. Here, the most important thing is, when a cell is highlighted by the selection as above, the value inside the cell is displayed at the sametime. So my question is, how can we do the same in JTable?
I have tried to do something similar using keyEvent listener, but the problem with that is, when a key event is generated, the next cell is being highlighted but the indices of the previous(which was previously highlighted) is being returned in the getSelectedRow() and getSelectedColumn() methods.
Also i tried the ListSelectionListener. but the same fault exists.
If there's any way to get the selected cell's indices immediately after the new cell is highlighted when navigated using arrow keys, that will work. Also an event should be generated since I want to update the formula bar as in Excel. Can someone help me with this?
Thanks in advance!
You can use this simple trick!
Only have to make two excess jTextfields. (can set to be invisible at the run time)
Try to get an idea from below code segment.
private int r;
private int c;
private String buffer;
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
jTextField2.requestFocus();
buffer = jTextField1.getText();
jTable1.getModel().setValueAt(jTextField1.getText(), r, c);
}
private void jTable1KeyTyped(java.awt.event.KeyEvent evt) {
r = jTable1.getSelectedRow();
c = jTable1.getSelectedColumn();
jTable1.putClientProperty("terminateEditOnFocusLost", true);
jTextField1.requestFocus();
}
private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {
buffer = (String)jTable1.getModel().getValueAt(r, c);
jTextField1.setText(buffer);
jLabel1.setText(buffer);
}
private void jTextField2FocusGained(java.awt.event.FocusEvent evt) {
buffer = jTextField1.getText();
jTable1.getModel().setValueAt(buffer, r, c);
jTextField1.requestFocus();
}

jTable function getSelectedRow(), getSelectedColumn() returning -1

I am new in Java programming. I need to get the indices of selected column and row. I am getting -1 as selected indices for both the column and row. I have searched for a solution but didn't find anything satisfactory.
My code is following:
private void deleteProductButtonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel tableModel = (DefaultTableModel) this.productDisplaTable.getModel();
JTable table = new JTable(tableModel);
int selectedRowIndex = table.getSelectedRow();
int selectedColIndex = table.getSelectedColumn();
System.out.println(selectedRowIndex );
System.out.println(selectedColIndex);
}
You're checking if a row is selected before the JTable has been displayed before the user can even interact with it.
Instead why not have that code in an ActionListener or some other listener so that the user at least has a chance to select something? This suggests that you might have a misunderstanding on how event-driven programming works and need to study the concepts a little bit more.
What makes you think that creating a a new JTable would have any selected rows or columns
JTable table = new JTable(tableModel); //???
Try using a table that is actually visible to the user instead
In your code you create a new JTable but you don't add this component to any container. Thus it won't never be visible and no row nor column could ever be selected.
Now, while we can add components dynamically in Swing we tipically place all our components before the top-level container (window) is made visible. In this case you should place the table when you initialize your components (don't forget the scroll pane) and do whatever you need to do when the button is pressed.
On the other hand I'm not sure what are you trying to achieve. I mean you already have a table called productDisplaTable. If you want to print the selected row and column in that table then make this little change:
private void deleteProductButtonActionPerformed(java.awt.event.ActionEvent evt) {
//DefaultTableModel tableModel = (DefaultTableModel) this.productDisplaTable.getModel();
//JTable table = new JTable(tableModel);
int selectedRowIndex = this.productDisplaTable.getSelectedRow();
int selectedColIndex = this.productDisplaTable.getSelectedColumn();
System.out.println(selectedRowIndex );
System.out.println(selectedColIndex);
}
Thanks all for taking time to reply.
I got the answer I was looking from #dic19's comment.
Now I clearly see the mistake I was doing. This was due to my lack of knowledge in Java programming.

jTable select only data where checkbox is chceck

Hi I have a problem with separate data in jTable.
My jTable:
When I click to Second button, so I have two data in jTable.
It's correct but when I click to First button again I get same jTable that as jTable in Second button.
This is my code:
DefaultTableModel model = new DefaultTableModel();
model = (DefaultTableModel) jTable1.getModel();
for(int i = 0; i < jTable1.getRowCount(); i++)
{
if(jTable1.getValueAt(i, 0) == Boolean.FALSE)
{
model.removeRow(i);
}
}
jTable2.setModel(model);
But it doesn't work. Is there anyone who tells me why ?
But it doesn't work. Is there anyone who tells me why ?
When you remove, for example, row 0, then all the rows shift down by one, but the value of "I" keeps increasing by one so you will "skip" rows every time you remove a row.
The solution is to start on the last row and decrement "I":
for(int i = jTable.getRowCount() - 1; i >=0; I--)
It's not a problem.
Yes it is. You posted example only works because you selected every other row in the table. Try selecting the first two rows and see what happens. Have said that, this is not the real solution to your problem, because you should NOT be removing data from the first TableModel.
It's correct but when I click to First button again I get same jTable that as jTable in Second button.
The problem is that you can't delete the data from the first TableModel. You need to create a new TableModel and then "copy" the data from the first TableModel to the second TableModel.

Questions about Jtable. Click within particular column perform event, is this possible?

I've added several rows to a Jtable, and I don't know if it's possible but I'd like if you click on any cell within a particular column then the connecting row is removed.
Are functions like this possible?
(I'm not asking anyone to do all the work for me. Just asking for information or a tutorial link) thanks :-)
attach a mouse listener to the table and when mouse click event occurs if column matches your particular column then remove that row.
tbl.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int row = tbl.rowAtPoint(e.getPoint());
int col = tbl.columnAtPoint(e.getPoint());
if(col == SPECIFIC_COLUMN_INDEX){
((DefaultTableModel)tbl.getModel()).removeRow(row);
}
}
});

Categories