Hello I am working on a project with a JTable to join words. In the table words that have been joined together have an # character between them.
I basically want to remove all the rows in the table containing the character #. This is what I have tried so far:
for (int i = 0; i < table.getRowCount(); i++) {
if ((boolean)table.getValueAt(i, 0).equals("\\b[#]+\\b")) {
table.remove(i);
}
}
This code is not working as intended. I would like to know the correct way to write this code. Thank you for any replies in advance.
Your code calls the remove() method inherited from the Container class - you want to manipulate the table model used by your table. Assuming that you're using a DefaultTableModel, you can get the model from the table and use the removeRow() method.
Also, .equals("\\b[#]+\\b") doesn't check for a String containing the '#' character. It checks for an exact match of the text that you specified. You might want to look at the String.contains(...) method.
Remember that the data in a Swing JTable is stored in an underlying TableModel, not in the JTable object itself. Something like this should work.
DefaultTableModel model = (DefaultTableModel) table.getModel();
for (int i = 0; i < model.getRowCount(); i++) {
if (model.getValueAt(i, 0) != null && model.getValueAt(i, 0).toString().contains("#")) {
model.removeRow(i);
}
}
Related
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;
}
}
I'm newer to java as am a migrant from vb6 presnelty I'm shifting my staff and old equipments for last 15 years to Java now i would to load data isnide my Jtable relay on No. of records i mean i want to test where is the current records inside my Jtable and then upload my records behind that line my functions as per here under i used jtable number of row but it gave me error message
public void LoadLineInJtable(){
int RowNo= jTable1.getModel().getRowCount();
jTable1.setValueAt(jTjournal_submain_no.getText(), RowNo+1, 0);
jTable1.setValueAt(jTjournal_submain_name.getText(), RowNo+1, 1);
}
when trying with above code gave me below error
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 9 >= 8
at java.util.Vector.elementAt(Vector.java:470)
thank you for your input .
Your JTable's row count is RowNum (which you should rename rowNum to comply with Java naming standards), and then you try to set values at a row that doesn't yet exist. Understand that JTable rows are 0 based, like Java arrays, and so you cannot manipulate the data of anything beyond the rowCount - 1.
If you want to add a row, you must use either the addRow(...) if your model is a DefaultTableModel or a child of this class, or else use your own add row method if you're using a custom table model.
So you might want something like this:
public void LoadLineInJtable(){
// get data and put into array or Vector
String[] dataRow = {
jTjournal_submain_no.getText(),
jTjournal_submain_name.getText()
};
// get table model and cast it to a DefaultTableModel
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
// add row to model
model.addRow(dataRow);
}
use this to add a new row at the end of table:
((DefaultTableModel)jTable1.getModel()).addRow(new String[]{"column1","column2"});
I have a program that is written to work in conjunction with a JTable and a few other Swing elements in order to display and model a backend for a game. The function is supposed to get the first row selected and the last row selected and store them in an array rows at index 0 and 1 respectively. Thanks for your help and hope to understand what is going on here.
public int[] getRows(JTable table) {
rows = new int [2];
rows[0] = table.getSelectedRow();
rowCount = table.getSelectedRowCount() - 1;
rows[1] = rows[0] + rowCount;
return rows;
}
JTable.getSelectedRows() can you help you in this case. Just take the first and last index from the array it returns. Note that it can return an empty array.
I'm having difficulties getting the following code to preserve the logically selected row in the model if the JTable has been sorted.
It works as intended when no sorting is applied.
private void updateAccountTable() {
accountsTable = guiFrame.getAccountsTable();
// Preserve selected model row
String accountNumber = "";
int selectedRow = accountsTable.getSelectedRow();
if(selectedRow >= 0){
accountNumber = (String)accountsTable.getValueAt(selectedRow, 0);
}
// Preserve sort order
// Keep eclipse happy. better way??
List <? extends SortKey> keys = accountsTable.getRowSorter().getSortKeys();
// Update displayed accounts
DefaultTableModel model = (DefaultTableModel) accountsTable.getModel();
model.getDataVector().clear();
Object[][] tableContents = accountList.getAccountsAsArray(true);
model.setDataVector(tableContents, tableHeaders);
model.fireTableDataChanged();
// reset sort order
accountsTable.getRowSorter().setSortKeys(keys);
// If updated model contains previously selected account, reselect
if (!accountNumber.equals("") && null != accountList.getAccount(accountNumber)){
for (int row=0; row<accountsTable.getRowCount(); row++){
String an = (String)accountsTable.getValueAt(row, 0);
if (an.equalsIgnoreCase(accountNumber)){
accountsTable.setRowSelectionInterval(row, row);
break;
}
}
}
else {
accountsTable.clearSelection();
}
}
Unfortunately setRowSelectionInterval() doesn't updated the selected row as expected, despite being called with the correct view row number. It seems to do nothing.
.....So,
Why is setRowSelectionInterval() failing to updated the selection, or what have I missed?
The row obtained from getSelectedRow() is in view coordinates, while the model coordinates have been changed by the intervening update. Quoting from the relevant tutorial section:
This distinction does not matter unless your viewed data has been rearranged by sorting, filtering, or user manipulation of columns.
You will need to use the conversion methods described near the end of Sorting and Filtering, which suggests:
When using a sorter, always remember to translate cell coordinates.
When you click on Jtable header to sort it, and click on a row (ex. 3rd row), you will get the value of unsorted JTable's row. To avoid this situation, use this LOC.(ik this is irrelvant to what you're trying to do but for others w/ similar problems)
int row = tblUser.getSelectedRow();
//Without below line, the value you get would be the row before sorting
int correctModel = tblUser.convertRowIndexToModel(row);
//Get username and use it to find its corresponding tuple
String username = (tblUser.getModel().getValueAt(correctModel, 1)).toString();
My table looks like this and Im trying to get the username of the selected row and w/o the 2nd LOC, I'd get the unsorted JTable's row value even after sorting it:
---------------------
| id | username |
---------------------
| | |
I have a JTable with some columns. I have a HashMap of the column identifier mapped to the position in the view, for example:
TableHeader1 | TableHeader2 | TableHeader3
sth. sth. sth.
I know that:
TableHeader1 -> position 0
TableHeader2 -> position 1
TableHeader3 -> position 2
Now I want to reorder the columns. I know that there is a function called moveColumn(A, B) within the JTable class. This moves a column from A to B, and B is putted left or right.
My problem is, I want to order the whole table in a specific way, how can I do this?
If I use moveColumn, I cannot know where B has been moved, in 5 out of 10 cases it might be the right side and in the other cases the wrong side.
Hope you understand my problem :-)
You can change the columns order by removing all of them and adding them in the right order:
public static void setColumnOrder(int[] indices, TableColumnModel columnModel) {
TableColumn column[] = new TableColumn[indices.length];
for (int i = 0; i < column.length; i++) {
column[i] = columnModel.getColumn(indices[i]);
}
while (columnModel.getColumnCount() > 0) {
columnModel.removeColumn(columnModel.getColumn(0));
}
for (int i = 0; i < column.length; i++) {
columnModel.addColumn(column[i]);
}
}
OK how about this. Might be a bit left field.
Extend TableColumn and give your new class a position property. Have it implement Comparable and use the position to compare columns.
Next, extend DefaultTableColumnModel and store TableColumns in an ordered list.
Your JTable should now display columns according to their position. Untested but it sounds interesting so I might give it a go later.
Based on #Guillaume answer I found a way to do that without the need to remove all columns and add them again.
public static void setColumnOrder(int[] indices, JTable table, TableColumnModel columnModel) {
for (int i = 0; i < indices.length; i++) {
columnModel.moveColumn(i, table.convertColumnIndexToView(indices[i]));
}
}
This works better for me because with (SwingX) JXTable, the order of the invisible columns is not modified.
If you want to reorder by column name then you can check out the Table Column Reordering suggestion.
This problem can be solved by using the built in moveColumn function as a bubble sort shortcut. The hashmap holds your weights in that case. Keep in mind that getColumnModel().getColumn(j).getModelIndex() can be seen as the initial column index / ID that will not change. See it as a column title.
HashMap<int, int> mapOrder = new HashMap<int, int>();
for (int i = 0; i < jt_table.getColumnCount(); i++) {
for (int j = 0; j < jt_table.getColumnCount() - 1; j++) {
int col1 = mapOrder.get(jt_table.getColumnModel().getColumn(j).getModelIndex());
int col2 = mapOrder.get(jt_table.getColumnModel().getColumn(j + 1).getModelIndex());
if (col1 > col2) {
jt_table.moveColumn(jt_table.getColumnModel().getColumn(j).getModelIndex(), jt_table.getColumnModel().getColumn(j + 1).getModelIndex());
}
}
}