this function should refresh my JTable:
list = null;
list = (ArrayList<String[]>) interface_engine.getData();
info = new String[list.size()][header.length];
Iterator it = list.iterator();
for (int i = 0; i < list.size(); i++) {
String[] current = (String[]) it.next();
for (int j = 0; j < header.length; j++) {
info[i][j] = current[j];
}
}
DefaultTableModel model = (DefaultTableModel) data_table.getModel();
model.addRow(info);
when i call it for add a new row (getData is a remote method for retrieve data from db), the added row it's not display as a string, but a a variable reference (such as String#128dda...). Where's the problem?
the added row it's not display as a string, but a a variable reference (such as String#128dda...).
Read the DefaultTableModel API. You can't add a 2-Dimensional array using the addRow() method. You can only add one row at a time.
The addRow() method should be inside your loop. Build one row of data, then invoke the addRow() method.
Related
I'm trying to loop through all of the rows in a column in a jTable at the moment I can get it to loop through a column but it only gives me the first 5 values and it also gives me a strange output.
here is the code:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// Button to Start
Object[] columnData = new Object[jTable1.getColumnCount()];
Object[] rowData = new Object [jTable1.getRowCount()];
for (int i = 0; i < jTable1.getColumnCount(); i++) {
columnData[i] = jTable1.getValueAt(i, 4);
System.out.println(Arrays.toString(columnData));
}
here is the output:
I think you are using your column iteration as the row number in your code. jTable1.getValue(i, 4) has parameters row, column in that order. If you only have five columns, you will only get five values.
Try changing the loop to count through the rows and select the 5th column.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// Button to Start
Object[] columnData = new Object[jTable1.getRowCount()]; // One entry for each row
Object[] rowData = new Object [jTable1.getRowCount()];
for (int i = 0; i < jTable1.getRowCount(); i++) { // Loop through the rows
// Record the 5th column value (index 4)
columnData[i] = jTable1.getValueAt(i, 4);
}
System.out.println(Arrays.toString(columnData));
I want to add jTable elements to a list. It works fine when jTable have more then one element, but it gives me the the following error when jTable have one element. Why so? How to resolve it. Thank You.
Here is the error.
Error: Exception in thread "AWT-EventQueue-0"
java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
Here is the code:
DefaultTableModel table_tags = (DefaultTableModel)this.jTable_selectedTags.getModel();
int rowCount=table_tags.getRowCount();
Vector data = table_tags.getDataVector();
Vector row = (Vector) data.elementAt(1);
int mColIndex = 0;
List tags_data = new ArrayList(rowCount);
for (int i = 0; i < table_tags.getRowCount(); i++) {
row = (Vector) data.elementAt(i);
tags_data.add(row.get(mColIndex));
}
System.out.println(tags_data);
The issues was in accessing of index. So, after changing
Vector row = (Vector) data.elementAt(1);
to
Vector row = (Vector) data.elementAt(0);
It worked fine.
Your for loop is wrong. You iterate the table using this condition:
for (int i = 0; i < table_tags.getRowCount(); i++)
Problem is that you use the row count to perform the iteration. Given only one element in the Vector your row count would indeed by 1 but using this to iterate over the table would cause it to fail, since the only element at the table would at index 0. Change your above condition to:
for (int i = 0; i < table_tags.getRowCount() - 1; i++)
And I suppose you'll be fine.
I need convert HashMaps to xlsx using poi. For sheet data2 i need something like that:
table1:
But i have table2:
Here's my list of HashMaps:
rows=[{kol2=s, kol1=s}, {kol2=bbbb, kol3=bbbb, kol1=aaaa}, {kol2=bbbb, kol3=bbbb, kol1=aaaa}, {kol2=bbbb, kol3=bbbb, kol1=aaaa}, {kol2=s, kol1=s}]}
Here's my code:
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet("data");
XSSFSheet sheet2 = workBook.createSheet("data2");
int rowCount = 0;
int help = 1;
List<HashMap<String, Object>> rows = ((List<HashMap<String, Object>>) x);
int rowCount2 = 0;
int header = 1;
Row header2 = sheet2.createRow(0);
for (int i = 0; i < rows.size(); i++) {
int li = 0;
Row row2 = sheet2.createRow(++rowCount2);
HashMap<String, Object> row = rows.get(i);
int columnCount2 = 0;
for (HashMap.Entry<String, Object> subElement : row.entrySet()) {
if (subElement.getValue() != null) {
if (i == li) {
Cell cell = header2.createCell(header);
cell.setCellValue(subElement.getKey().toString());
header++;
}
li++;
Cell cell2 = row2.createCell(++columnCount2);
cell2.setCellValue(subElement.getValue().toString());
}
}
}
Someone can help?
Iterating over a HashMap's EntrySet
The first problem is that you are iterating over the entrySet of your HashMap
for (HashMap.Entry<String, Object> subElement : row.entrySet()) {
// no guaranteed order
}
Looking at the JavaDoc of the Set#iterator() method you will see this:
Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).
There are Sets which are ordered (such as the TreeSet), but since you are using a HashMap, your EntrySet won't be ordered too.
Notice the column order in your sheet is kol2-kol3-kol1. Don't you want it to be kol1-kol2-kol3?
Not creating empty columns
You are forgetting to create empty cells for columns you don't have in your Map.
if (subElement.getValue() != null) {
// there won't be an empty cell if you e.g. don't have kol2 in your rows Map,
// since this just skips your current value
}
This is why you end up with something like:
kol2 kol3 kol1
s s
bbbb bbbb aaaa
...
instead of:
kol2 kol3 kol1
s s
bbbb bbbb aaaa
...
Creating the header row inside the loop
By creating the header row inside your loop, you are making your solution more complicated than necessary. It would be much easier just to create the header row and then loop over your entries in the List.
if (i == li) {
Cell cell = header2.createCell(header);
cell.setCellValue(subElement.getKey().toString());
header++;
}
If you are doing this outside the loop, there is no need for the li and the header variable
Suggested solution
I would (for a start) come up with something like this (I added some extra comments I normally wouldn't put there to make more clear what the intentions are and what aspects of the solution you need to understand):
XSSFSheet sheet2 = workBook.createSheet("data2");
List<HashMap<String, Object>> rows = ((List<HashMap<String, Object>>) x);
List<String> headers = Arrays.asList("kol1", "kol2", "kol3");
int currentRowNumber = 0;
// create header row
Row header = sheet2.createRow(currentRowNumber);
for (int i = 0; i < headers.size(); i++) {
Cell headerCell = header.createCell(i);
headerCell.setCellValue(headers.get(i));
}
// create data rows (we loop over the rows List)
for (int i = 0; i < rows.size(); i++) {
HashMap<String, Object> row = rows.get(i);
// we neet to increment the rowNumber for the row in the sheet at the beginning of
// each row. entry 0 in the rows List is in sheetRow 1, entry 1 in sheetRow 2, etc.
currentRowNumber++;
Row sheetRow = sheet2.createRow(currentRowNumber);
// we can now loop over the columns inside the row loop (using the headers List)
// we create a Cell for each column, but only fill it if there is
for (int j = 0; j < headers.size(); j++) {
Cell cell = sheetRow.createCell(j);
// only fill the cell if we are having data in the row map for the current column
String currentColumnName = headers.get(j);
if (row.containsKey(currentColumnName)) {
cell.setCellValue(row.get(currentColumnName).toString());
}
}
}
If you want a different column order, just change the header List and you are done (e.g. Arrays.asList("kol2", "kol3", "kol1")).
The Array data[][] stores the right values inside the loop.
Then I add the array to an ArrayList, but it's like all objects inside the ArrayList are being updated when I change the value of my data array after that.
How can I store the value of each Object[][] separately?
for (int i = 0; i < Materia.length; i++) {
for (int j = 0; j < Materia[i].Aluno.length; j++) {
data[j][0] = Materia[i].Aluno[j].Nome;
System.out.println(data[j][1] = Materia[i].Aluno[j].Nome);//checking outpit, its displaying the correct data I want
data[j][1] = Materia[i].Aluno[j].nota;
data[j][2] = Materia[i].Aluno[j].frequencia;
}
tabs.add(data); //arraylist to storer object data
tabela[i] = new JTable((Object[][]) tabs.get(i), Names);//populate default table model
conteudo2[i] = new JPanel();
conteudo2[i].add(new JLabel(Materia[i].Nome));
conteudo2[i].add(new JScrollPane(tabela[i]));
}
You add your data array (of arrays) to the tab-List.
Since you don't create a new object before adding it to the arrayList, it's the same object, and therefore you also update the contents in the data-Array, when you update the object in the tab-List.
You need to create a new data-Array, before adding it to the list.
You can achieve this by creating a new 2d-Array with the method System.arrayCopy before you add this new object to you tabs-List:
Object[][] myDataCopy = new Object[data.length][];
for(int i = 0; i < data.length; i++) {
myDataCopy[i] = new XXYY[d.length];
System.arraycopy(data[i], 0, myDataCopy[i], 0, data[i].length);
}
I have a jTable and it's got a table model defined like this:
javax.swing.table.TableModel dataModel =
new javax.swing.table.DefaultTableModel(data, columns);
tblCompounds.setModel(dataModel);
Does anyone know how I can clear its contents ? Just so it returns to an empty table ?
Easiest way:
//private TableModel dataModel;
private DefaultTableModel dataModel;
void setModel() {
Vector data = makeData();
Vector columns = makeColumns();
dataModel = new DefaultTableModel(data, columns);
table.setModel(dataModel);
}
void reset() {
dataModel.setRowCount(0);
}
i.e. your reset method tell the model to have 0 rows of data The model will fire the appropriate data change events to the table which will rebuild itself.
If you mean to remove the content but its cells remain intact, then:
public static void clearTable(final JTable table) {
for (int i = 0; i < table.getRowCount(); i++) {
for(int j = 0; j < table.getColumnCount(); j++) {
table.setValueAt("", i, j);
}
}
}
OK, if you mean to remove all the cells but maintain its headers:
public static void deleteAllRows(final DefaultTableModel model) {
for( int i = model.getRowCount() - 1; i >= 0; i-- ) {
model.removeRow(i);
}
}
//To clear the Contents of Java JTable
DefaultTableModel dm = (DefaultTableModel) JTable1.getModel();
for (int i = 0; i < dm.getRowCount(); i++) {
for (int j = 0; j < dm.getColumnCount(); j++) {
dm.setValueAt("", i, j);
}
}
You have a couple of options:
Create a new DefaultTableModel(), but remember to re-attach any listeners.
Iterate over the model.removeRow(index) to remove.
Define your own model that wraps a List/Set and expose the clear method.
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 contains 40 raws, you can do following.
DefaultTableModel model = (DefaultTableModel)this.jTable.getModel();
model.setRowCount(0);
model.setRowCount(40);
One of the trivial methods is to use the following option.
dataModel.setRowCount(0);
dataModel is the model which you would like clear the content on
However, it is not optiomal solution.
Another easy answer:
defaultTableModel.getDataVector().removeAllElements();