Get rows from a jtable sorted with RowSorter - java

Actually i am able to export as excel but it export the entire JTable not the sorted data with Rowsorter, i tried something like but nothing changed :
DefaultTableModel tableModel;
try {
RowSorter<? extends TableModel> rowSorter = model.getjTable1().getRowSorter();
TableModel tableModel = rowSorter.getModel();
} catch (NullPointerException ne) {
tableModel = (DefaultTableModel) model.getjTable1().getModel();
}
A second important thing about my jtable, actually i can select only 1 row and i wont be able to change that.
My question, is, how can i only get the sorted rows from RowSorter ?
Do i need to sort programmatically ? Can i get the visible rows from my jtable ?

but it export the entire JTable not the sorted data
The data in the TableModel does NOT change.
Only the data displayed in the JTable (the view) changes.
If you only want the data in the table then you only use methods of the JTable to access the data.
Something like:
for (int row = 0; row < table.getRowCount(); row++)
for (int column = 0; column < tagle.getColumnCount(); column++)
System.out.println( table.getValueAt(row, column);

Related

Using result set to add dynamic JCheckBox

I saw this Need to add JCheckBox In JTable Dynamically but it didn't help at all seeing my situation is similar but I am not sure how to add the JCheckBox after I have take the raw data from my database.
public void fillAnyTable(ResultSet resultSet, JTable table)throws SQLException{
//Create new table model
DefaultTableModel tableModel = new DefaultTableModel();
//Retrieve meta data from ResultSet
ResultSetMetaData metaData = resultSet.getMetaData();
//Get number of columns from metadata
int columnCount = metaData.getColumnCount();
//Get all column names from metadata and add columns to table
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++){
tableModel.addColumn(metaData.getColumnLabel(columnIndex));
}
//this is when I assume I can create a new column but now how to add the checkbox
tableModel.addColumn("Check");
//Create Array of Objects with size of Column count from metadata
Object[] row = new Object[columnCount];
//Scroll through Result Set
while (resultSet.next()){
//Get object from column with specific index of result set to array of objects
for (int i = 0; i < columnCount; i++){
row[i] = resultSet.getObject(i+1);
}
System.out.println(Arrays.toString(row));
//Now add row to table model with that array of objects as an argument
tableModel.addRow(row);
}
//Now we add the table model to the table
table.setModel(tableModel);
}
}
This is what the view looks like
I am not sure how to add the JCheckBox after I have take the raw data from my database.
You don't add a JCheckBox. The TableModel holds data, not components. So you need to:
override the getColumnClass(...) method of the TableModel to return Boolean.class for the column where you want the check box. Then the table will use the proper renderer/editor for a check box.
add Boolean.FALSE to the TableModel when you add the data from the ResultSet.
So you just add the Boolean value when you are finished adding each column value to your row array:
//Now add row to table model with that array of objects as an argument
row[columnCount].add( Boolean.FALSE );
tableModel.addRow(row);
Of course you will also need to make your "row" array larger to hold this value.

Modify Entire Column(s) in JTable

I have a JTable which is formed by importing data from a text file. It is a huge table with about 522 columns and thousands of rows. Many cells in this table are empty as well.
Now, I want to be able to apply some mathematical operations to the data available in certain columns. So right now, I can select multiple columns, but I dont know how to go about getting these values. I know I'll need an array of arrays where I can store the value from the table columns and then modify each value based on my algorithm.
Right now, to start it off simply, I just want to be able to print out the values in the select column (just one to keep it simple) but I cant do that, I get the value of a particular cell printed 2-4 times. My testing code is as follows:
For Selection entire columns, I am using this code:
public static void selectWholeColumn(final JTable table)
{
final JTableHeader header = table.getTableHeader();
header.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
int col = header.columnAtPoint(e.getPoint());
if(header.getCursor().getType() == Cursor.E_RESIZE_CURSOR)
{
e.consume();
}
else
{
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
table.clearSelection();
table.setColumnSelectionInterval(col,col);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
}
});
}
In my GUI I have a button which when clicked fires a backend class and this method which takes in a JTable as a parameter is executed to print out the values of all rows in the selected Column:
public void filterData(final JTable table)
{
TableModel model = table.getModel();
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
cellSelectionModel.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
String selectedData = null;
int[] selectedRow = table.getSelectedRows();
int[] selectedColumns = table.getSelectedColumns();
for (int i = 0; i < selectedColumns.length; i++)
{
for (int j = 0; j < selectedRow.length; j++)
{
selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
}
}
System.out.println("Selected: " + selectedData);
}
});
Any suggestions as to how I could print or basically get the values of all rows in a selected Column or columns, so that I can modify the data in them at once?
Thank you!
Looping though the TableModel and using getValueAt() in a ListSelectionListener is a reasonable approach, although your listener will be invoked for each change. It's not clear where you're having trouble; you can
Concatenate the selected values using StringBuilder.
Accumulate the selected values in a List<String>.
Maintain the selection in your TableModel, as shown here using Set<Integer>.
Operate on the selection in the ItemHandler of a TableCellRenderer, as shown here.

How to check if table is made in Jtable and JFrame

Hi I want to check if table is made to add rows.If is not I want to show message :create table first. My problem : I do not know what I should type to if statement to check if is although one row made(which can suggest me that table was created).
I create table via NetBeans JFrame options this way:
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
/*
space is empty here because on start I do not create any rows.
user has to click button create or add rows.
*/
},
new String [] {
"Name", "Surname"
}
));
My if statment:
if(//do not know what type here because new Object [][] will not work){
JOptionPane.showMessageDialog(null, "Create table!");
}else //add row to table because exist {
Object[][] temp = new Object[data.length + 1][2];
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < 2; j++) {
temp[i][j] = data[i][j];
}
}
data = temp;
jTable1.setModel(new DefaultTableModel(data, columns));
}
Looks like you're using NetBeans GUI builder. If you go to the properties pane (the tab to the very right in Netbeans design view) with the jTable highlighted, you will see a property model
Click on the ... button to the right of the property, and a Dialog will pop up
Set the number of rows to 0, and the number of columns to how many columns you want, and set the column title and type and if you want it editable
Then in your actionPerformed, however you get the data for rows, add an array of that data to the model with model.addRow()
public void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// get row data, and put it into an array
Object[] row = {data1, data2, data3 ...};
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.addRow(row);
}
So whenever the button is pressed, a row will be added dynamically to your table. That's the easiest way to do it with GUI Builder
EDIT
If you want to check the number of rows then you check the rowCount
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
if (model.getRowCount() < 1) {
do something.
}

How can I delete the column and its underlying data without hiding it in jtable

I am having difficulties with deleting the actual data under a particular column which I am trying to delete.
I actually want to delete the column and its underlying data. I am able to insert new columns but when I delete
and insert again, the old columns which I previously deleted pop up again.
Any sort help is appreciated.
Thank you in advancce.
The data is stored in the TableModel.
Deleting the column from the ColumnModel will only prevent the view (the JTable) from showing it.
In order to remove it, you need to tell the TableModel to remove the column data as well.
Depending on you implementation, you could use JTable.setValueAt(value, row, column) or TableModel.setValueAt(value, row, column), which ever is more convenient.
This of course assumes you've implemented the setValueAt method
public void removeColumnAndData(JTable table, int vColIndex) {
MyTableModel model = (MyTableModel)table.getModel();
TableColumn col =table.getColumnModel().getColumn(vColIndex);
int columnModelIndex = col.getModelIndex();
Vector data = model.getDataVector();
Vector colIds = model.getColumnIdentifiers();
// Remove the column from the table
table.removeColumn(col);
// Remove the column header from the table model
colIds.removeElementAt(columnModelIndex);
// Remove the column data
for (int r=0; r<data.size(); r++) {
Vector row = (Vector)data.get(r);
row.removeElementAt(columnModelIndex);
}
model.setDataVector(data, colIds);
// Correct the model indices in the TableColumn objects
// by decrementing those indices that follow the deleted column
Enumeration<TableColumn> enum1 = table.getColumnModel().getColumns();
for (; enum1.hasMoreElements(); ) {
TableColumn c = (TableColumn)enum1.nextElement();
if (c.getModelIndex() >= columnModelIndex) {
c.setModelIndex(c.getModelIndex()-1);
}
}
model.fireTableStructureChanged();
}
/*MyDefaultTableModel class**/
class MyTableModel extends DefaultTableModel
{
String columns[];
int size;
public MyTableModel(String col[],int size)
{
super(col,size);
columns = col;
this.size=size;
}
public Vector getColumnIdentifiers()
{
return columnIdentifiers;
}
}

JTable's and DefaultTableModel's row indexes lose their synchronization after I sort JTable

JAVA
NETBEANS
// resultsTable, myModel
JTable resultsTable;
DefaultTableModel myModel; //javax.swing.table.DefaultTableModel
myModel = (DefaultTableModel) resultsTable.getModel();
// event of clicking on item of table
String value = (String) myModel.getValueAt(resultsTable.getSelectedRow(), columnIndex)
I use JTable and DefaultTableModel to view a table of various info
and I want to get a value of a certain column of the selected index of the table.
The code I wrote above works fine except when:
I use the sort of the GUI (click on the field name I want to sort on the table)
The table is properly sorted but after that when I select a row, it gets
the value of the row that was there before the sort.
This means that after sorting (using the JTable's GUI)
the 'myModel' and 'resultsTable' objects have different row indexes.
How do I synchronize those two?
You need to use the 'convertXXX' methods on the JTable see the JavaDoc
int row = resultsTable.getSelectedRow();
if (row != -1) {
row = table.convertRowIndexToModel(row);
String value = (String) myModel.getValueAt(row, columnIndex)
A problem with using the JTable.getValueAt() is to get the column you want. When the columns are moved around in the GUI the indexes "change" to match the view. By using the AbstractTableModel.getValueAt() and the JTable.convertXXX() (as outlined by Guillaume) it's just a matter of using the column indexes for the model when retrieving data.
Except from the solution Guillaume gave (Thanks)
I did this:
// resultsTable, myModel
JTable resultsTable;
DefaultTableModel myModel; //javax.swing.table.DefaultTableModel
myModel = (DefaultTableModel) resultsTable.getModel();
// event of clicking on item of table
String value = (String) **resultsTable**.getValueAt(resultsTable.getSelectedRow(), columnIndex)
I used the resultsTable Object instead of the myModel Object to get the value.

Categories