getting sum of jtable values continuously - java

I want to get the sum of all the values from jtable continuously. Like I have made a jtable where the user will put data continuously and whenever a new row will insert in the jtable then some code should execute for taking all the sum of values of jtable and then set it on a text filed. I have written the code but I don't that in which event I should use the code so that when a new row is inserted in the table then the code runs and get the new sum of all values and store in a text field. So now in which method of jtable I should use this code so when a new row is inserted so that code executes.
The code is here...
int rows=productionTable.getRowCount();
int totalBundles=0;
int totalBoxes=0;
//totalBundles
for(int i=0;i<rows;i++)
{
totalBundles=totalBundles+Integer.parseInt(productionTable.getValueAt(i, 1)+"");
}
this.totalBundlesTextField.setText(totalBundles+"");
//
//totalBoxes
for(int i=0;i<rows;i++)
{
totalBoxes=totalBoxes+Integer.parseInt(productionTable.getValueAt(i, 2)+"");
}
this.totalBoxesTextField.setText(totalBoxes+"");
//

So now in which method of jtable I should use this code so when a new row is inserted so that code execute
You do this when the data in the TableModel changes. So you can add a TableModelListener to the TableModel of your table. Then a TableModelEvent will be generated when you:
add rows of data
remove rows of data
change the value of existing data
In each of the above cases you could then iterate through the TableModel to calculate the new value.
Check out JTable -> TableModeListener for a simple example of use a TableModelListener.
The above approach assumes that you don't have a lot a data in your model, since it recalculates the value each time a change is made.
If you have a lot of data this is not very efficient so you may want to keep a running total of the value in your TableModel. So you would need to customize the TableModel to keep a total. And then in methods like setValueAt(...), insertRow(...), removeRow(...) you would need to add logic to update the total as the model is updated.

Related

How to get data on JTable when using RowSorter?

I am having problem in getting the data when selecting a row from a JTable. This happens whenever I enable setAutoCreateRowSorter(true) of the table. So far this is what I did:
private void displayBooks(){
bookTable.setAutoCreateRowSorter(true);
bookTable.getTableHeader().setFont(new java.awt.Font("Century Gothic", 1, 14));
dtm = (DefaultTableModel) bookTable.getModel();
clearTable(dtm);
for(Book book: books){
dtm.addRow(new Object[]{book.getId(), ...//rest of the code
}
}
On the bookTableMouseClicked method this is what I did:
...
if(bookTable.getSelectedRow() >= 0){
Book book = books.get(bookTable.getSelectedRow());
setBook(book);
}...
I am now having ambiguous data when I clicked the header table to sort the data.
The selected row number on a JTable instance is always the selected row number on the view side.
If you activate row sorters this no longer matches the row number on the model side.
To transform between these two row numbers the JTable offers methods for converting from "view row index" to "model row index" and vice versa. These methods are named convertRowIndexToModel and convertRowIndexToView.
In your mouseClicked handler you need to call the function convertRowIndexToModel as follows:
if (bookTable.getSelectedRow() >= 0){
Book book = books.get(bookTable.convertRowIndexToModel(bookTable.getSelectedRow()));
setBook(book);
}
The problem is that you are storing data in two places:
in the TableModel
in an ArrayList
The data should only be stored in the TableModel. This way you don't need to worry about syncing the data since it is only in one place.
You could simply create a Book object from the selected row by using getValueAt(..) method of the JTable. You would need to invoke that method for each column in the table.
Or the other approach is to create a custom TableModel that holds Book objects, then you could just get the Book object directly from the table. This is a little more work, but it is the better approach.
Check out Row Table Model for a step-by-step approach on how to create a custom TableModel for a custom object.

Check if a JTable exists and add rows to it if it does

I am building an application in Swing where data is being fetched from the DB and populated on the GUI in a JTable.
Before the first run, there is no JTable on the GUI. Once the data is fetched for the first time, the JTable gets created and populated.
First issue:
I need this data to keep refreshing on the JTable.
Second Issue:
In the second run, I want to add a row to the JTable instead of creating a new one. So it should check whether the JTable exists or not and accordingly create a new one or add a row.
You could just always create and add an empty table to the frame.
Then when you execute your code you just check the number of rows in the table:
If the number is zero then you create a new TableModel and use the setModel(...) method of the table to add the data to the table.
If the number of rows is greater than zero then you can use the addRow(...) method of your DefaultTableModel to add new rows of data.

how to add a column to a jTable and populate on the fly

i have a Jtable with 4 columns and 6 rows and a jButton. when the jButton is clicked a query runs and the results are stored in a string variable. after the query has successfully completed additional code s called to add a column to the existing jTable. My problem is how do i then populate the newly created column with data from the String variable. Am using the following code below
for(int col = 0; col<jTable2.getRowCount(); col++){
TableColumn c = new TableColumn();
c.setHeaderValue("Test");
((DefaultTableModel) jTable2.getModel()).addColumn(c);
jTable2.setValueAt("100", col, 12);
}
this works but the problem is that the code also adds additional columns that are equivalent to the set condition in the forloop. how to i get it to only add one column and populate as much as the condition set in the forloop without also add multiple columns. I know my problem comes from the forloop but i do not know how to solve it.
can onion assist
Add the column outside the for loop and set values in the loop for each row.

How to add checkboxes to a JTable which uses a model with values from a database?

I have a model(AbstracTableModel) which I use to build a JTable.
The thing is that the table cell values seen in the GUI are displayed from a database.
How can I add a new column with checboxes for each row of the table?
Is there a concrete answer to this?
The thing is that the table cell values seen in the GUI are displayed from a database.
Use a DefaultTableModel to store the data from the database.
See the TableFromDatabaseExample.java code found in Table From Database for simple code to load the DefaultTableModel.
How can I add a new column with checboxes for each row of the table?
You can modify the above code to add an extra column to the "columnNames" Vector. Then in the looping code you add a Boolean.FALSE object to the "row" Vector.
Or, after creating the DefaultTableModel with the data from the database you can use the addColumn(...) method of the DefualtTableModel to create your column of check boxes.

How can delete/hide the mid row(5)th row before it listed in jtable

Here i have an 1-10 row is listed in jtable i want to delete/hide the 5th row before it listed in jtable.
i set the rowheight but it affected the cellselection.Is there any way to hide/delete the row without affected the normal flow code?
If i remove the row it will throws ArrayIndexoutofBoundException.
in my project executed means one gui open in that gui listed the some string. In here we can add the more string via Add Button on popup Button
Here what i need is i have to hide the particular string. That string is placed on 1st row.
i need to hide the string from end user.
now u hope understand.
You can use the JTable row filtering support in order to hide certain rows without deleting them from the model. Also see this: How can I filter rows in a JTable?
You can eliminate rows in the table by calling the removeRow() method. If you want to just hide it instead of elimintaing it you need to customize the JTable's model to meet your specs on what to display.
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
using DefaultTableModel with JTable you should be able to use model.removeRow(int row) function to remove A row from JTable. There is no way to hide a row based on index as much as i know. However, If you need to hide and re-show mechanism you need to save the row prior to delete it and Save the removedRow in a ArrayList to re-use them.. Something as follows:
List<Vector>deletedRows = new ArrayList<>();
Vector removingRow = (Vector) model.getDataVector().get(5);
deletedRows.add(removingRow);
model.removeRow(5);

Categories