Populating jtable from array under a loop - java

On each loop, it collects info from a certain file and stores it's contents in an array. The array should then create a new row per loop on the table. My problem is, is that it only creates 1 row. How can I fix this?
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
iCount = humanReadableByteCount(listOfFiles[i].length(), true);
if (files.toLowerCase().endsWith(".mp3"))
{
//jTextArea1.append("File name: " + files + " | Last Modified: " + sdf.format(listOfFiles[i].lastModified()) + " | Lenght: " + iCount + "\n");
Object rowData[] = { files, sdf.format(listOfFiles[i].lastModified()), iCount };
Object columnNames[] = { "Name", "Last Modified", "Size" };
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
model.addRow(rowData);
jTable1.setModel(model);
}
}
}

Create the model outside the loop. Set the table model outside the loop as well.
The only thing to do inside the loop is to add the new rows to the model.

You create a new model every time you cycle the loop. So every time, you have a new and empty model and you add 1 row to the empty model.
It should be like this:
Object columnNames[] = { "Name", "Last Modified", "Size" };
DefaultTableModel model = new DefaultTableModel(columnNames);
jTable1.setModel(model);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile() && listOfFiles[i].getName().toLowerCase().endsWith(".mp3"))
{
files = listOfFiles[i].getName();
iCount = humanReadableByteCount(listOfFiles[i].length(), true);
model.addRow(new Object[]{ files, sdf.format(listOfFiles[i].lastModified()), iCount });
}
}

Related

How to display Object array in JTable?

This is my code which I am using but when I am trying to print dataArray object, then data is not show in JTable. Which model properties of table to print Object array values can used and how?
public class ShowAddressForm extends javax.swing.JFrame {
Object data[][];
Object dataArray[][];
int count = 0;
String st;
public ShowAddressForm(String fname , String str) {
super(fname);
st = str;
initComponents();
fillTable();
}
public void fillTable()
{
int count = 0;
String str;
try
{
BufferedReader br = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = br.readLine()) != null)
{
count++;
}
br.close();
} catch (Exception e)
{
}
Object id;
Object name;
data = new Object[count][7];
int i = 0 , j = 0 , m;
try
{
BufferedReader buffrea = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = buffrea.readLine()) != null)
{
StringTokenizer token = new StringTokenizer(str , "*");
int n = token.countTokens();
id = token.nextElement();
name = token.nextElement();
String strNameLow = name.toString().toLowerCase();
String strNameUpp = name.toString().toUpperCase();
if(strNameLow.startsWith(st.toLowerCase()) || strNameUpp.startsWith(st.toUpperCase()))
{
data[i][0] = id;
data[i][1] = name;
for(j = 2 ; j < n ; j++)
{
data[i][j] = token.nextElement();
}
i = i + 1;
}
}
buffrea.close();
} catch(IOException ioe){
System.out.println("Error : " + ioe.toString());
}
dataArray = new Object[i][7];
for(int a = 0 ; a < i ; a++)
{
for(int b = 0 ; b < 7 ; b++)
{
dataArray[a][b] = data[a][b];
}
}
//Here is the code to print dataArray object which i used but it is not working, when i am run my program it is print "[Ljava.lang.Object;#1cc2e30" in table's first cell[0][0] position
DefaultTableModel model = (DefaultTableModel)this.data_table.getModel();
model.addRow(dataArray);
}
I filled data in a JTable like this. You might want to give it a try adapting it to your code. Variable and stuff are in spanish, just replace them with what you need. In my case it's a table with 4 columns representing a date, a score, duration and max viewers.
private void fillJTable(){
//creating data to add into the JTable. Here you might want to import your proper data from elsewhere
Date date = new Date();
UserReplay rep1 = new UserReplay(date, 12, 13,14);
UserReplay rep2 = new UserReplay(date, 2,34,5);
ArrayList<UserReplay> usuaris = new ArrayList<>();
usuaris.add(rep1);
usuaris.add(rep2);
//----Filling Jtable------
DefaultTableModel model = (DefaultTableModel) view.getTable().getModel();
model.addColumn("Fecha");
model.addColumn("Puntuación");
model.addColumn("Tiempo de duración");
model.addColumn("Pico máximo de espectadores");
for (int i = 0; i < usuaris.size(); i++){
Vector<Date> fecha = new Vector<>(Arrays.asList(usuaris.get(i).getDate()));
Vector<Integer> puntuacion = new Vector<>(Arrays.asList(usuaris.get(i).getPuntuacion()));
Vector<Integer> tiempo = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Integer> espectadors = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Object> row = new Vector<Object>();
row.addElement(fecha.get(0));
row.addElement(puntuacion.get(0));
row.addElement(tiempo.get(0));
row.addElement(espectadors.get(0));
model.addRow(row);
}
}

Repaired Records : Cell information from worksheet created

I'm receiving an error when opening my OpenXML created spreadsheet. The error is as follows.
repaired record : xl/worksheets/sheet.xml partial cell information
private void SavexlsExcelFile(String fullPathName)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Create(fullPathName, SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
Columns columns = new Columns();
worksheetPart.Worksheet.AppendChild(columns);
Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet" };
sheets.Append(sheet);
workbookPart.Workbook.Save();
sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
List<List<string>> dataRow = new List<List<string>>();
List<String> dtRow = new List<String>();
Row row = new Row();
for (int i = 0; i < dataGridView1.RowCount; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
if (i == 0)
{
Cell dataCell = new Cell();
dataCell.DataType = CellValues.String;
CellValue cellValue = new CellValue();
cellValue.Text = dataGridView1.Columns[j].Name;
dataCell.StyleIndex = 2;
dataCell.Append(cellValue);
row.AppendChild(dataCell);
//dataColumn.Add(dataGridView1.Columns[j].Name);
}
dtRow.Add(dataGridView1.Rows[i].Cells[j].Value.ToString());
}
}
dataRow.Add(dtRow);
sheetData.AppendChild(row);
row = new Row();
foreach (List<string> datarow in dataRow)
{
row = new Row();
foreach(string dtrow in datarow)
{
row.Append(ConstructCell(dtrow, CellValues.String, 2));
}
sheetData.AppendChild(row);
}
worksheetPart.Worksheet.Save();
}
}
private Cell ConstructCell(string value, CellValues dataType, uint styleIndex = 0)
{
return new Cell()
{
CellValue = new CellValue(value),
DataType = new EnumValue<CellValues>(dataType),
StyleIndex = styleIndex
};
}
There are 2 issues here that I can see. The first is that your use of Columns is incorrect. You should use Columns if you wish to control things such as the width of a column. To use Columns correctly, you'll need to add child Column elements. For example (taken from here):
Columns columns = new Columns();
columns.Append(new Column() { Min = 1, Max = 3, Width = 20, CustomWidth = true });
columns.Append(new Column() { Min = 4, Max = 4, Width = 30, CustomWidth = true });
In your sample you could just remove the following two lines
Columns columns = new Columns();
worksheetPart.Worksheet.AppendChild(columns);
The second issue is the StyleIndex you are using; the style doesn't exist in your document because you haven't added it. The easiest thing to do here is to just remove the StyleIndex altogether.
When debugging files like this, it's always worth looking at the OpenXml Productivity Tool. You can open a generated file in the tool and validate it to see what errors you have in your file.
All the text in Excel is stored under a shared string table. You need to insert the string in shared string table:
string text = dataGridView1.Columns[j].Name;
cell.DataType = CellValues.SharedString;
if (!_spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Any())
{
_spreadSheet.WorkbookPart.AddNewPart<SharedStringTablePart>();
}
var sharedStringTablePart = _spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
if (sharedStringTablePart.SharedStringTable == null)
{
sharedStringTablePart.SharedStringTable = new SharedStringTable();
}
//Iterate through shared string table to check if the value is already present.
foreach (SharedStringItem ssItem in sharedStringTablePart.SharedStringTable.Elements<SharedStringItem>())
{
if (ssItem.InnerText == text)
{
cell.CellValue = new CellValue(ssItem.ElementsBefore().Count().ToString());
SaveChanges();
return;
}
}
// The text does not exist in the part. Create the SharedStringItem.
var item = sharedStringTablePart.SharedStringTable.AppendChild(new SharedStringItem(new Text(text)));
cell.CellValue = new CellValue(item.ElementsBefore().Count().ToString());

Display JSON data in a ComboBox using java

I used the code below to retrieve json data and put it in a table. That worked. But I want to display the data in a combobox now. Right now, it is displaying the items in the dropdown in this format: ljava.lang.string #5c647e05
Can someone please tell me what I'm doing wrong? Thank you.
Hashtable response = parser.parse(reader);
java.util.List allResult = (java.util.List) response.get("AllResult");
System.out.println(allResult);
try {
String[][] data = new String[allResult.size()][4];
for (int i = 0; i < allResult.size(); i++) {
Object obj = allResult.get(i);
String result = (String) ((Hashtable) obj).get("Status");
String investorName = (String) ((Hashtable) obj).get("investorName");
if (result.equalsIgnoreCase("ok")) {
for (int j = 0; j < 4; j++) {
if (j == 0) {
data[i][j] = investorName; }
}
}
}
ComboBox investorNames = new ComboBox(data);
details.addComponent(investorNames);
System.out.println("Data here: " + data);
String[] columnNames = { "Seller's Name", "Stock Name", "Unit", "Price" };
TableModel model = new DefaultTableModel(columnNames, data, false);
Table table = new Table(model);
table.setScrollable(true);
details.addComponent(table);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Try to paste in Combobox only vector of invector names not whole array of arrays. As Combobox just invokes toString() on every array (row) of matrix, that's why you got Ljava.lang.String#5c647e05 and not investor names. Something like this:
String[] comboData = new String[allResult.size()];
for (int i = 0; i < allResult.size(); i++){
...
String investorName = (String) ((Hashtable) obj).get("investorName");
comboData[i] = investorName
...
}
ComboBox investorNames = new ComboBox(comboData);
details.addComponent(investorNames);
....
ComboBox expects an array of string but you are passing to it an array of array of strings.
So those ljava.lang.string #5c647e05 that you are seeing are the 'toString' representation of an array of strings.
You need to somehow (depending on what you need to do) flatten your 'data' so that it becomes an array of strings.

How to write only the 5th value from a list into a csv

I am reading several csv sheet with the opencsv libary. I am storing the "read" csv file in hugeList = reader.readAll(); Now I only want to only write the 5th value of this huge csv sheet columnwise in another sheet.
At the moment I am standing at:
//reading all entries in a huge list
//-740 as it would take to much time to run it in "dev mode"
for (int j = 0; j < (fileList.size() - 740); j++) {
String csvFile = "C:\\Users\\" + fileList.get(j);
reader = new CSVReader(new FileReader(csvFile), ';');
hugeList = reader.readAll();
List<String[]> data = new ArrayList<String[]>();
// for(int m = 0; m < hugeList.size(); m++) {
// String[] value = hugeList.get(m);
data.add(hugeList.get(5));
// }
writer.writeAll(data);
}
However I have no idea how to write them into another column and just take the 5th value?
I really appreciate your answer!
UPDATE 1
Goal: I have saved all values from one sheet at the time in hugeList. Now I want to
write only the 5th column into a new sheet.
Problem: The logic behind this goal.
UPDATE 2
This is what my code looks like right now:
//reading all entries in a huge list
for (int j = 0; j < (fileList.size() - 740); j++) {
String csvFile = "C:\\" + fileList.get(j);
reader = new CSVReader(new FileReader(csvFile), ';');
hugeList = reader.readAll();
List<String[]> data = new ArrayList<String[]>();
List<String> tmp= new ArrayList<String>();
for(int m = 0; m < hugeList.size(); m++) {
String[] values = hugeList.get(m);
tmp.add(values[0]);
}
data.add(tmp.toArray(new String[0]));
writer.writeAll(data);
}
As you can see I get my data still vertically... Why?
I thing you are already on the right way.
You have 2 possibilities.
1. data.add(hugeList.get(4));
2. for(int m = 0; m < hugeList.size(); m++) {
if(m==4){
String[] values = hugeList.get(m);
data.add(values);
break;
}
}
UPDATE
Goal: I have saved all values from one sheet at the time in hugeList. Now I want to write only the 5th column into a new sheet. Problem: The logic behind this goal.
My Approach for a result in rows
List<String[]> data = new ArrayList<String[]>();
List<String> tmp= new ArrayList<String>();
for(int m = 0; m < hugeList.size(); m++) {
String[] values = hugeList.get(m);
tmp.add(values[4]);
}
data.add(tmp.toArray(new String[0]));
}
My Approach for a result in Column
for (int j = 0; j < fileList.size(); j++) {
String csvFile = readPath + fileList.get(j);
System.out.println("Read: " + csvFile);
reader = new CSVReader(new FileReader(csvFile), ';');
hugeList = reader.readAll();
String[] data = new String[1];
for (int m = 0; m < hugeList.size(); m++) {
String[] values = hugeList.get(m);
data[0] = values[0];
writer.writeNext(data);
}
}

Jtable to Excel in Java

I created a registration form, that collects data from user, and display it into a Jtable, then I want to allow user to press a button to export the Jtable content to excel form. In the display table, it can show all user input, but when I export to excel, it only show columnNames and first row of data, so I want to know if I have done it wrong?
User input:
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
String[] columnNames = new String[] {"First Name", "Last Name", "Email", "Degree", "Year", "Event"};
Object[][] tabledata = new Object[1][6];
String fn = FirstName.getText();
String ln = LastName.getText();
String em = Email.getText();
String re = ReEnter.getText();
String de = Degree.getSelectedItem().toString();
String yr = Year.getSelectedItem().toString();
String ev = EventDate.getSelectedItem().toString();
ArrayList<String> data = new ArrayList<String>();
data.add(fn);
data.add(ln);
data.add(em);
data.add(de);
data.add(yr);
data.add(ev);
list.add(data);
//Set fields to empty
FirstName.setText("");
LastName.setText("");
Email.setText("");
ReEnter.setText("");
Degree.setSelectedItem(null);
Year.setSelectedItem(null);
EventDate.setSelectedItem(null);
// print data to table
Object[][] temp = new Object[tabledata.length+1][6];
for(int i=0;i<tabledata.length;i++){
for(int j=0;j<6;j++){
temp[i][j] = tabledata[i][j];
}
temp[tabledata.length-1][0]= fn;
temp[tabledata.length-1][1]= ln;
temp[tabledata.length-1][2]= em;
temp[tabledata.length-1][3]= de;
temp[tabledata.length-1][4]= yr;
temp[tabledata.length-1][5]= ev;
}
tabledata = temp;
table.setModel(new DefaultTableModel(tabledata, columnNames));
}
}
Export data to excel:
try {
TableModel model = table.getModel();
File file = new File("member.xls");
FileWriter output = new FileWriter(file);
for(int i = 0; i <model.getColumnCount(); i++){
output.write(model.getColumnName(i) + "\t");
}
output.write("\n");
for(int k=0;k<model.getRowCount();k++) {
for(int j=0;j<model.getColumnCount();j++) {
output.write(model.getValueAt(k,j).toString()+"\t");
}
output.write("\n");
output.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
![Run program] [1]: http://i.stack.imgur.com/T99L5.png
![Exported excel file][2]: http://i.stack.imgur.com/ZGy3Z.png
Check your bracketing :P
You call output.close() inside the first for-loop for printing out data. This closes the file before getting to the 2nd row and onwards.

Categories