JTable becomes blank after executing update on table? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to write some software where when a user adds a new entry to a SQL database, my JTable showing the entries in the database updates. Currently, when the method updateTable(Object[][] data) is called, it results in the table becoming blank.
Would anyone know of a fix for this type of issue?
Here is the code for the method:
/**
* This method updates the JTable which shows the Amp Settings.
*
* #param data A 2D Array of Objects witch represents the data in the
* database.
*/
private void updateTable(Object[][] data)
{
// A new DefaultTableModel.
DefaultTableModel dtm = new DefaultTableModel();
// Looping over the data, create a new row and add it to the DataModel.
for (int i = 0; i < data.length; i++)
{
Object[] row = new Object[data[i].length];
// Fill the row's data.
for (int j = 0; j < row.length; j++)
{
row[j] = data[i][j];
}
// Set the row in the table model.
dtm.addRow(row);
}
// Set the model of the table to the newly created DefaultTableModel.
table.setModel(dtm);
((AbstractTableModel) table.getModel()).fireTableDataChanged();
}
Here is the code which calls updateTable():
// Calls update table, SERVER.dbtoArray() returns a 2D Array of objects.
updateTable(SERVER.dbToArray());

DefaultTableModel dtm = new DefaultTableModel();
Even though you add data to the TableModel you didn't add any column names so as far as the table is concerned there are 0 columns to display.
Your code should be something like:
String[] columnNames = { "Column1", "Column2", "..." );
DefaultTableModel dtm = new DefaultTableModel(columnNames, 0);
Or a better approach would be to use:
DefaultTableModel dtm = (DefaultTableModel)table.getModel();
dtm.setRowCount(0);
This will keep the existing columns and just add the data.
Also you don't need to recreate the row array. You already have the data as a row in your 2D array:
for (int i = 0; i < data.length; i++)
{
Object[] row = data[i];
model.addRow( row );
}

Related

Save Selected JTable Rows and Show them in another JTable (in another JFrame)

I have a table with some data. I want to select a couple of rows which I want to monitor (I will then display these rows in a new JFrame with its own table) - let's call this monitored records.
I have this piece of code I found that does this exactly, but it creates the new table with the same number of rows as the original table. It however does show the new selected rows successfully but it populates the new table from the bottom going up.
For instance my original table has 10 rows, I select 3, the new table will have 10 rows in total, but only 8, 9 and 10 are populated with the selected data and rows 1 to 7 just have empty cells.
How do I make it only show the selected data and not the empty rows?
public void exportSelectedRows(ActionEvent actionEvent) {
TableModel tableModel = patientTable.getModel();
int[] index = patientTable.getSelectedRows();
Object[] row = new Object[10]; //problem is here that object has size 10 hence the 10 rows?
monitoredPatients = new MonitoredPatients();
monitoredPatients.monitoredPatientsTable = new JTable(row.length, columnNames.length);
DefaultTableModel defaultTableModel = (DefaultTableModel) monitoredPatients.monitoredPatientsTable.getModel();
for (int value : index) {
row[0] = tableModel.getValueAt(value, 0);
row[1] = tableModel.getValueAt(value, 1);
row[2] = tableModel.getValueAt(value, 2);
row[3] = tableModel.getValueAt(value, 3);
row[4] = tableModel.getValueAt(value, 4);
row[5] = tableModel.getValueAt(value, 5);
defaultTableModel.addRow(row);
}
monitoredPatients.add(new JScrollPane(monitoredPatients.monitoredPatientsTable));
}
I expect the new table to only show the selected records with no empty rows.
row = new Object[10]; //problem is here that object has size 10 hence the 10 rows?
..
monitoredPatients.monitoredPatientsTable = new JTable(row.length, columnNames.length);
Well you have a couple of problems:
Why would you create the row Array with a value of 10? The row array represents the data for each row. You only copy 6 columns of data, so the size of the array should only be 6.
The value for the number of rows should be 0, since you are starting with an empty DefaulotTableModel. You then use the addRow(...) method to add a new row of data. This makes the size of your TableModel dynamic.
So the code should be:
monitoredPatients.monitoredPatientsTable = new JTable(0, columnNames.length);
Or better yet, why don't you create the TableModel with the array containing the name of the columns? I'm sure you don't want to see "A, B, C, D, E, F", which will be the default if you just specify the number of columns. Read the DefaultTableModel API for the appropriate constructor to use.

How to load or refresh jTable's data everytime I add new data to ArrayList Object [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Load/refresh jTable everytime I inserted new set of data to arrayList
Already tried those lines I've put on comments but still nothing changed. Consider that adding of those data to arrayList are performed in separate class.So here, Action performed in a jButton so everytime I add set of data from jTextfields and stores it as Object to arrayList, only the first set of columns and rows I inserted to the arrayList are the only displayed data in jTable. Although the second set of data I inserted after clicking the jButton twice was saved to arrayList, the jTable didn't even refresh or load the new data I inserted. Any help will be appreciated
//BUTTON ACTION PERFORMED
DefaultTableModel tableModel = (DefaultTableModel) MyJTable.getModel();
tableModel.fireTableDataChanged();
//tableModel.setRowCount(0);
//tableModel.repaint();
//int rowCount = tableModel.getRowCount();
//for(int i = rowCount -1; i >= 0; i--){
//tableModel.removeRow(i);
//}
Object[][] displayOnTable = new Object[Data.data.size()][4];
for(int x=0; x < Data.data.size(); x++){
displayOnTable[x] = Data.data.get(x);
}
MyJTable.setModel(new javax.swing.table.DefaultTableModel(
disp,
new String [] {
"ID", "Name", "Gender", "Age"
} ));
// --- Declared in Separated class----
//public class Data {
// public static List<Object[]> data = new ArrayList<>();
// }
// ------------------------
Already tried those lines I've put on comments but still nothing changed.
Well start with something really simple.
Add two lines to your ActionListener:
DefaultTableModel tableModel = (DefaultTableModel) MyJTable.getModel();
tableModel.setRowCount(0);
If nothing happens to the data in the table, then it means you don't have a reference to the table that is visible on the frame. So you need to solve this problem.
Did the data in the table clear? If so this is a good sign as it means your code is referencing the TableModel of the JTable that has been added to the frame.
So now you can add data from the ArrayList.
The basic logic would be:
System.out.println( data.size() ); // to verify you actually have data in the List
for (Object[] row: data)
model.addRow( row );
That's it. No need to create a new TableModel. No need to create a 2D array. You will simply iterate through the ArrayList adding one row of data at a time to the model. Then the table will automatically repaint() itself.
Of course this will only work if you have data in the ArrayList.

JTable sorting not the good value in the cell

I am using NetBeans to write a program. I create a JTable with the design and I add rows to the table without any problem.
When I click on the tab to sort the table it works, with setAutoCreateRowSorter(true). However when I try to get the value of the updated cell it is not the good one. Indeed, it is the value of the previous cell, when I fill my table.
This is how I add row to my table:
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
for (int i = 0; i < arrayPep.size(); i++) {
model.addRow(new Object[]{arrayPep.get(i).getPeptide(), arrayPep.get(i).getStart(), arrayPep.get(i).getStop(), arrayPep.get(i).geteValue(), arrayPep.get(i).getName()});
}
This is how I try to get the value of the cell:
DefaultTableModel model = (DefaultTableModel) table.getModel();
table.getModel().getValueAt(rowSelected, 0);
How could I fix this ?
You are indexing the model with an index from the view. First convert the view index to a model index using JTable.convertRowIndexToModel(rowSelected):
int modelRowSelected = table.convertRowIndexToModel(rowSelected);
table.getModel().getValueAt(modelRowSelected, 0);
For some context regarding view indexes and model indexes, please read this answer I gave on the topic.

After sorting a jtable how can I number a column?

Hello am developing a Java Desktop result system I have succeeded in sorting my J table with respective to the column average Am still trying to give positions to the students after the J table has been sorted so that each student gets his or her position basing on his or her average this is what I have done so far..`
//Sorts j Table basing on column average
public void checkPosition(){
//Erases column s/no
jTable1.getColumnModel().getColumn(0).setMinWidth(0);
jTable1.getColumnModel().getColumn(0).setMaxWidth(0);
jTable1.getColumnModel().getColumn(0).setWidth(0);
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(jTable1.getModel());
jTable1.setRowSorter(sorter);
List<RowSorter.SortKey> sortKeys = new ArrayList<>(2000);
sortKeys.add(new RowSorter.SortKey(jTable1.getColumnCount()-2, SortOrder.DESCENDING));
//sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);
positionInsert();
}
public void positionInsert(){
//Inserts position at last column "position"
int pos=1;
for(int g=0; g<jTable1.getRowCount(); g++){
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setValueAt(pos, g, jTable1.getColumnCount()-1);
pos++;
}
}
However it still doesn't work the position is still faulty Screenshot of j table
The table is seen at the link above my english is not that good but help will be much appreciated thanks
When you sort a table the data in the table model doesn't change, only the order in which the data is displayed in the table.
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setValueAt(pos, g, jTable1.getColumnCount()-1);
The above code assumes that the data in the model is in the same order as the table which is wrong when you sort of filter a table.
You need to update the data in the model via the table:
table.setValueAt(pos, g, jTable1.getColumnCount()-1);
The table will now convert the row of the table to the row of the model before updating the model.
Or if you want to update the model directly, you are responsible for converting the table row to the model row. This is done by using the convertViewToModel(...) method of the JTable.

load text file of 100 records 10 by 10 jtable java?

!I have file which has 100 records, I used Jtable to show records 15 by 15 and go on. I am new to JFC concepts, I created a jtable with 15 rows, in my jtable first 15 rows displaying flawless. From 16th row onwards,it does not show any records. My question is how to display next 15 records in the same jtable? and go on till the end of the text file.
Finally, i need to Remove the empty rows.`
for (int initial = 0; initial < rowLength; initial++)
{
for (int j = 0; j < aIndex; j++)
{
TableData[initial][j] = cName[k];
System.out.println(TableData[initial][j]);
k++;
}
}` And I not used any scrollpanes specifically.
Write your own TableModel for your JTable. Use a AbstractTableModel it should be easy and configurable enough for you program!
In the Model you have to use a constructor, this should look like this:
public Model(ArrayList<Object[]> data, String[] header) {
this.data = data;
this.header = header;
}
At the beginning use two private fields, to save and work with your data in your TableModel:
private ArrayList<Object[]> data;
private String[] header
If you have already a TableModel use a Method that sets the data in your Table, like:
public void setTableData(ArrayList<Object[]> data) {
this.data = data;
fireTableDataChanged();
}
Importent is that you fire the table and notify listeners with fireTableDataChanged() or somthing similar(only specifed cells for example)!
At the line where you want to change the Data use:
Model model = (Model) table.getModel();
model.setTableData(data);

Categories

Resources