JTable returning JTable when calling getModel() - java

My JTable is declared as so:
String[] cols = {"Name","Location"};
String[][] data = new String[][] {{"Name","Location"}};
JTable table = new JTable(data, cols);
So i came across a problem when trying to update my JTable's data... I'm suppose to be adding a new row to the table. Here is my code for that:
data = new String[][] {{"Name","Location"}{"Name1","Location1"}};
DefaultTableModel dm = (DefaultTableModel)(table.getModel());
dm.fireTableDataChanged();
For some reason i get an error on the Line:
DefaultTableModel dm = (DefaultTableModel)(table.getModel());
The error shown is...
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JTable$1 cannot be cast to javax.swing.table.DefaultTableModel
at client.pages.ClientPage.update(ClientPage.java:171)
Line 171 of my ClientPage.java is the above line of code that i said the error is on.
Anyone know why its doing this?
table.getModel(); //Suppose to return TabelModel not JTable

table.getModel() isn't returning a JTable, it's returning an anonymous class in JTable that extends TableModel. Therefore, table.getModel() is indeed returning the correct class type.
The error occurs, however, because you try to cast this anonymous table model to DefaultTableModel, which is another subclass of TableModel, but is not the type being returned by table.getModel().
To fix this, simply treat the table model as the interface type TableModel; don't assume it's a DefaultTableModel.

Start by taking a look at How to Use Tables and the JavaDocs for DefaultTabelModel
You should change the way you are creating the table and model to something more like...
String[] cols = {"Name","Location"};
String[][] data = new String[][] {{"Name","Location"}};
JTable table = new JTable(new DefaultTableModel(date, cols));
JTable(Object[][], Object[]) actually uses it's own implementation of a the TableModel
Next, change....
data = new String[][] {{"Name","Location"}{"Name1","Location1"}};
DefaultTableModel dm = (DefaultTableModel)(table.getModel());
dm.fireTableDataChanged();
to something more like...
data = new String[][] {{"Name","Location"}{"Name1","Location1"}};
DefaultTableModel dm = (DefaultTableModel)(table.getModel());
dm.fireTableDataChanged();
to something more like...
data = new String[] {"Name1","Location1"};
DefaultTableModel dm = (DefaultTableModel)(table.getModel());
dm.addRow(data);

Related

Turning ArrayList of Rows into a JTable

I decided it would be easiest to store my data in a custom Row object based on this post
Java data structure to store tabular data
But Im wondering how I actually go onto then create a JTable with this Array of row objects
My current attempt starts out looking like this:
public class TestTable extends JTable {
private final String[] columnNames = {"col1", "col2", "col3"};
public TestTable() {
DefaultTableModel model = new DefaultTableModel(columnNames, 10); //10 is just a placeholder for the number of rows as I dont know how to add the data yet
}
}
My data would be stored in an ArrayList that looks like this:
Row row1 = new Row("1", "2", "3");
ArrayList<String> data = new ArrayList<String>;
data.add(row1);
data.add(row2);
...
data.add(row10);
where my final ArrayList would just look like a list of row objects
List<String> data = List.of("1", "2", "3" );
model.addRow(data.toArray());
would be a simple approach

Get sorted TableModel

I am trying to get the sorted TableModel of a JTable which is done by the following simple regex criteria:
try {
TableRowSorter<TableModel> sortRow = new TableRowSorter<>(testTable.getModel());
testTable.setRowSorter(sortRow);
String sortString = "Something";
sortRow.setRowFilter(RowFilter.regexFilter("(?i)" + sortString));
}
which will sort the data according to sortString.
But when I try to do the following :
try {
TableRowSorter<TableModel> sortRow = new TableRowSorter<>(testTable.getModel());
// ....
// previous code
// ....
TableModel tM = testTable.getModel();
someOtherTestTable.setModel(tM); //<---Here
}
It provides me the DefaultTableModel. So, my question is this: How do I get the sorted TableModel so that I can post to another JTable?
A TableRowSorter conditions the view, JTable; the model, TableModel, remains unchanged. If the underlying model of the RowSorter remains the same, you should be able apply the old TableRowSorter to the new JTable using setRowSorter().
…
someOtherTestTable.setModel(tM);
someOtherTestTable.setRowSorter(sortRow);

Implementing few excel functionality using JTable

I am trying to implement Summation function of MS EXCEL but not getting a way to get the values from the JTable cells. Can you suggest me some way to get the values from the cells and use it for my function?
For example, how can you get the value -
String data[][] = {{"Value1", "Value2", "Value3"},{"Value4", "Value5", "Value6"},
{"Value7", "Value8", "Value9"},{"Value10", "Value11", "Value12"}};
String col[] = {"Column1", "Column2", "Column3"};
DefaultTableModel model = new DefaultTableModel(data, col);
JTable table = new JTable(model);
...
System.out.println(table.getModel().getValueAt(2, 2)); // row index and column index
...
it gives -
Value9
To get the values ​​from the table, you can implement the interface MouseListener in the anonymous inner class, for example -
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JTable target = (JTable) e.getSource();
int rowIndex = target.getSelectedRow();
int columnIndex = target.getSelectedColumn();
System.out.println(target.getModel().getValueAt(rowIndex, columnIndex));
}
});
See also:
How to Write a Mouse Listener
How to Write a List Selection Listener

Setting the TableModel on an already constructed Table

You can create a table model and add it to a table
TableModel tm = new TableModel();
JTable table = new JTable(tm);
however, if I init a Table
JTable table = new JTable();
and then create a table model later on...
TableModel tm = new TableModel();
tm.addValueAt(...);
...
Is there a way I can add this table model to the original table?
I've actually created my own classes to extend TableModel and JTable, and I thought that I could simply reconstruct the table given the new table model, but this doesn't seem to work.
As stated here: JTable, You can use setModel(TableModel)
public void setModel(TableModel dataModel)
Sets the data model for
this table to newModel and registers with it for listener
notifications from the new data model.

how to clear JTable

How can i clear the content of the JTable using Java..
You must remove the data from the TableModel used for the table.
If using the DefaultTableModel, just set the row count to zero. This will delete the rows and fire the TableModelEvent to update the GUI.
JTable table;
…
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
If you are using other TableModel, please check the documentation.
Basically, it depends on the TableModel that you are using for your JTable. If you are using the DefaultTableModel then you can do it in two ways:
DefaultTableModel dm = (DefaultTableModel)table.getModel();
dm.getDataVector().removeAllElements();
dm.fireTableDataChanged(); // notifies the JTable that the model has changed
or
DefaultTableModel dm = (DefaultTableModel)table.getModel();
while(dm.getRowCount() > 0)
{
dm.removeRow(0);
}
See the JavaDoc of DefaultTableModel for more details
I had to get clean table without columns. I have done folowing:
jMyTable.setModel(new DefaultTableModel());
This is the fastest and easiest way that I have found;
while (tableModel.getRowCount()>0)
{
tableModel.removeRow(0);
}
This clears the table lickety split and leaves it ready for new data.
I think you meant that you want to clear all the cells in the jTable and make it just like a new blank jTable.
For an example, if your table is myTable, you can do following.
DefaultTableModel model = new DefaultTableModel();
myTable.setModel(model);
If we use tMOdel.setRowCount(0); we can get Empty table.
DefaultTableModel tMOdel = (DefaultTableModel) jtableName.getModel();
tMOdel.setRowCount(0);
((DefaultTableModel)jTable3.getModel()).setNumRows(0); // delet all table row
Try This:

Categories

Resources