JTable getModel().setValueAt removing first element from array - java

I'm encountering an odd bug while updating the contents of a JTable. I've got a two dimensional array which is storing arrays of values to be displayed by the table (I'm only displaying one row of data at a time). When the user clicks a button, the next set of values (along with the next set of column headers) is displayed, and when the user clicks another button, it displays the previous set. The problem is that the first time I call getModel().setValueAt, on the first array in the two dimensional array, it is removed.
Here's the code that updates the JTable:
for(int i = 0; i < formattedData[displayedDataSet].length - 1; i++) {
TableColumn col = displayTable.getTableHeader().getColumnModel().getColumn(i);
col.setHeaderValue(WeatherData.WEATHER_MAP_KEYS[displayedDataSet * 5 + i]);
displayTable.getTableHeader().resizeAndRepaint();
displayTable.getModel().setValueAt(formattedData[displayedDataSet][i], 0, i);
}
for(String s: formattedData[0]) {
System.out.println(s);
}
I expect the output to be the first array in formattedData, but it is the second. However, commenting out the line with displayTable.getModel().setValueAt causes the correct result to be output. Why is this happening, and how can I update the JTable while preserving my array?

Related

How to add values from a column of a multipage column to an array?

I have a table with multipage. I want to add all the values in a particular column to a two-dimensional array. I first stored the values in the first page to an array(25 values in 1st page), clicked to the second page (4 values in 2nd page) and tried to store it in the array as a loop. The array is getting created, but lots of null values are also getting added. Here is my code:
Here pcount is number of pages, ccount = no. of rows in a page
for (int i=1; i< =pcount; i++)
{
for (int j=0;j< ccount; j++)
{
Array [i][j]=T.getcolumn.get(j).getText();
}
if(i<pcount)
T.getbutton().get(i).click(); //for clicking to the next page
}
If I print the values inside the loop, it prints correctly with the first page having 25 values and the 2nd page having 4 values
But if print it again using the below code, I see so many null values added to the array values:
for (int i=1; i< =Array.length; i++)
{
for (int j=0;j<Array[i].length; j++)
{
System.out.println(Array[i][j]);
}
}
Can anyone guide me why null values are getting added to my array

How to remove rows with certain values from Jtable?

I have a Jtable that I've loaded with values from a .csv file, but it creates a new row for every instance of 5/13/2013 that shows up in the file, like so:
I'd like to remove all rows with this info from the table, but am not sure how to do so. Any suggestions for me?
Here's my code to add the data to the table, if it helps:
while (inputStream.hasNext()) {
String data = inputStream.next();
String[] values = data.split(",");
tableModel.insertRow(tableModel.getRowCount(), values);
}//end of while block`
To reiterate and be completely clear, I want to remove every row that contains "5/13/2013" from the table completely. And I'm using the deafault table model, by the way.
I ended up applying a for loop and an if statement to get this working for me.
//remove rows with instances of "5/13/2013"
for (int i = 0; i < tableModel.getRowCount(); i++) {
if (((String)tableModel.getValueAt(i, 0)).equals("5/13/2013")) {
tableModel.removeRow(i);
}//end of if block
}//end of for block
It's worked well for me and has gotten rid of each of those rows. Hopefully this may help someone else out.
while(i < tableModel.getRowCount()) {
//if the value at (i, 0) match the specified value the row will be removed
/*
if the row removed all row will move up and their index will be changed
so you have to add a condition if the value from the table doesn't match
the specified value the iterator i will iterate by one to jump to the next
row
*/
if (((String)tableModel.getValueAt(i, 0)).equals("5/13/2013")) {
tableModel.removeRow(i);
}else {
++i;
}
}

JTable stop cell editing without user click

I'm trying to solve a strange problem with my program. This program creates a series of GUI's and JTables that give a user the ability to generate an XML file. One of these tables is for creating the "statements". I won't get into detail as far as that except to say that the data is stored in multiple 2D arrays which are in turn stored in a hash map.
Here is what happens. When a user enters the Statement screen a JTable is generated using the contents from the 2D array. This data populates the cell's which the user is able to modify. One of these cells (and the most important) is the amount. The amounts they set for the rows much match another amount from another class.
At the bottom of the table is a "finished" button. When the user clicks this button the logic will check to see if the money amounts match. If they do then the program will update the 2D array with any changed values and dispose of the JTable.
My problem is that once a user updates a cell and clicks "finished" the last updates made do not work. Essentially the user must first click somewhere else in the table and THEN hit finished. I would like this action to happen automatically so that when the user clicks "finished" cell editing is stopped. Here is the code for the finished button:
finishedButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
//Creates another table model for the finished button logic.
DefaultTableModel dm = (DefaultTableModel)StatementGUI.tbl.getModel();
//Gets the total number of table rows.
int rows = dm.getRowCount();
//Creates a variable to store the statement transaction total.
double statementTransactionTotal=0;
//For each row in the table.
for(int i = 0; i < dm.getRowCount(); i++){
//Gets the total of all transactions in the table.
String currentTotal = tbl.getValueAt(i, 3).toString();
Double currentTotalDouble = Double.parseDouble(currentTotal);
statementTransactionTotal=statementTransactionTotal+currentTotalDouble;
}
//Creates a decimal format and applies the statement total.
DecimalFormat df = new DecimalFormat("0.00");
String currentTotalDF = df.format(statementTransactionTotal);
//Stops editing on the table so that the data can be used.
if(null != tbl.getCellEditor()){
tbl.getCellEditor().stopCellEditing();
}
//If the statement total matches the transaction total..
if(currentTotalDF.matches(ClearedMainGUI.currentTransactionAmount)){
//For each row in the table..
for(int i = 0; i < dm.getRowCount(); i++){
//Will replace the hash/array value with the table value.
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][0]=tbl.getValueAt(i, 0).toString();
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][1]=tbl.getValueAt(i, 1).toString();
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][2]=tbl.getValueAt(i, 2).toString();
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][3]=tbl.getValueAt(i, 3).toString();
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][4]=tbl.getValueAt(i, 4).toString();
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][5]=tbl.getValueAt(i, 5).toString();
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][6]=tbl.getValueAt(i, 6).toString();
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][7]=tbl.getValueAt(i, 7).toString();
}
//For each row in the table..
for(int i = rows - 1; i >=0; i--){
//Removes the current row so the table will be empty next time.
dm.removeRow(i);
}
//Removes the frame and goes back to the previous GUI.
frame.dispose();
//If the statement total and transaction total do not match..
}else{
JOptionPane.showMessageDialog(null, "The statement total entered: $"+statementTransactionTotal+" " +
"does not match the transaction total of: $"+ClearedMainGUI.currentTransactionAmount);
}
}
});
I think my problem is with this line:
if(null != tbl.getCellEditor()){
tbl.getCellEditor().stopCellEditing();
}
This only seems to work once the user has clicked another area of the table after editing a cell.
I appreciate the help!
My problem is that once a user updates a cell and clicks "finished" the last updates made do not work.
Check out Table Stop Editing for two approaches:
You can either:
Add code to the ActionListener:
if (table.isEditing())
table.getCellEditor().stopCellEditing();
or set a property on the table:
JTable table = new JTable(...);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
Edit:
When the user clicks finished all the cell data will be saved to a 2D array.
Why? All the data is already stored in the TableModel.
In any case you need to stop editing BEFORE you attempt to copy data from the TableModel to the Array.

Removal of rows in table not working properly

I'm trying to remove the rows of data that are inside of my table when a button is clicked. My current code removes the row content after 1-3 presses, but I was hoping it would clear the content and then add the new content all in one press.
Here is the code I'm using...
private void newTasksActionPerformed(java.awt.event.ActionEvent evt) {
int sizeOfLL = taskLL.size();
DefaultTableModel textArea = (DefaultTableModel)jTable1.getModel();
int r = textArea.getRowCount();
for(int i = 0; i < r; i++) {
textArea.removeRow(i);
}
for (int i =0; i < sizeOfLL; i++) {
textArea.addRow(new Object[]{taskLL.get(i).index, taskLL.get(i).taskName, taskLL.get(i).taskDes, taskLL.get(i).taskStatus});
}
}
5 rows of data is shown in the jTable. After pressing the button again, two rows of data are deleted. If I press the button and 2nd time 1 row of data is left. Pressing the button a third time all rows of are removed and the next button press inserts 5 rows of data. Ideally I would want this button to always clear the row field and then add the data being inserted. Making every button press show fresh data as I have three buttons that have the exact same code but enter different data into the jTable.
You should try counting backwards from r-1 to 0. The problem is that the first row is removed, shifting the second row to that index. When you increment i, you are indexing past that row.
...
for (int i = r-1 ; i >= 0 ; i--) {
...

how to use convert model of Jtable

I have a jTable and I want to delete selected rows:
for( int i=0; i<selectedRows.length ; i++){
defaultablemodel.removeRow( selectedRows[i] - i);
int viewRowIndex = jTableMyTable.convertRowIndexToView(i); <<--- convert it here?
}
I searched around and most suggestions whenever delete rows, we should convert row index to view. Is the above correctly implemented?
I hit this problem because after i sorted my rows, i am unable to delete the row sometimes. but after sorting again i am able to delete a row. So i believe I need to use this convertRowIndexToView method.
You should actually be using
convertRowIndexToModel - Maps the index of the row in terms of the view to the underlying TableModel. If the contents of the model are not sorted the model and view indices are the same.
You have your selected rows, which are the selected indices in the view. So you need to convert those indices to the model indices before deleting.
When you use convertRowIndexToView, you're actually doing the opposite, trying to convert the model index to the table index.
" Is the above correctly implemented?"
First thing, when you want to remove rows this way, you should be traversing the indices backwards, from the last row up. The reason is that when you remove a row, the indices change. So you loop should go backwards like
int [] selectedRows = table.getSelectedRows();
for (int i = selectedRows.length - 1; i >= 0; i--) {
int viewIndex = selctedRows[i];
int modelIndex = table.convertRowIndexToModel(viewIndex);
model.removeRow(modelIndex);
}
The point is you want to remove the highest index first and work your way down to the lower indices.

Categories