List of file names in a table - java

I want to create a Swing gui where when I click browse I should get a text field giving the directory's path and a table of all the files in that directory.
I was able to get the first part(i.e. path). Can somebody help me in getting the files in a table?
I tried this:
public void jButton1ActionPerformed(ActionEvent e) {
JFileChooser filesave = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"TEXT File", ".txt", "text");
filesave.setFileFilter(filter);
int returnVal = filesave.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
File file = filesave.getSelectedFile();
PrintWriter os = new PrintWriter(file + ".txt");
for (int row = 0; row < jTable1.getRowCount(); row++) {
for (int col = 0; col < jTable1.getColumnCount(); col++) {
os.print(jTable1.getColumnName(col));
os.print(": ");
os.println(jTable1.getValueAt(row, col));
}
}
os.close();
System.out.println("Done!");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}

Well, nothing is added to the table because you didn't add anything to the table, no surprise here. If you ask me, some information is missing, but the normal way to achive this is...
create a TableModel (by extending AbstractTableModel)
set it in the JTable
when your button is clicked, update the TableModel, which should notify the listeners
Bingo, your table is updated
You can use a DefaultTableModel for that, no problem here. Search for it and you'll find enough tutorials go get by.

Related

Issue while writing cells in excel file using apache POI

I am facing issue while writing the data to excel file.
I am using apache POI 4.1.2 version library.
Below is the sample code.
try {
outputStream = new FileOutputStream(EXCEL_FILE_PATH);
} catch (Exception e) {
System.out.println("Exception While writing excel file " + e.getMessage());
}
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("FileCompare");
Row row = sheet.createRow(0);
Cell cellfilename = row.createCell(0);
cellfilename.setCellValue("File Name");
Cell cellfilename1 = row.createCell(1);
cellfilename1.setCellValue("Difference in File 1");
Cell cellfilenam2 = row.createCell(2);
cellfilenam2.setCellValue("Difference in File 2");
for (int diffcol = 1; diffcol < 3; diffcol++) {
for (int i = 1; i < 57; i++) {
Row rows = sheet.createRow(i);
// System.out.println("Difference Coln number " + diffcol);
Cell diffcell = rows.createCell(diffcol);
diffcell.setCellValue("abacds");
/*
* Cell diffcell2 = row.createCell(2); diffcell2.setCellValue("abacds");
*/
}
}
try {
workbook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStream.flush();
outputStream.close();
workbook.close();
}
In this only last column cells is getting saved in excel file , previous cells are kept as blank.
Kindly help and let me know if I am doing something wrong?
Not sure about the actual api but I think you inner loop should create columns and your outer one should create rows like this
for (int row=1:row<57;row++)
{
Row rows = sheet.createRow(row);
for (int diffCol = 1; diffCol < 3; difCol++)
{
Cell diffcell = rows.createCell(diffcol);
diffcell.setCellValue("abacds");
}
}
The problem is that inside your loop you're always using sheet.createRow(i) to retrieve the row you need, but as the docs says (docs that are written not so clear, actually) this method is always recreating a brand new & empty row, deleting the existing one (if a row at that i-position was already present).
It means that each iteration of yuor loop is actually deleting previous rows creating brand new rows: at the end only rows created by the last iteration are surviving!
To solve you're problem, use sheet.createRow(i) only one time in order to create the row at i-position and then only use sheet.getRow(i) to retreive it.
So replace (in your code) the following wrong line
Row rows = sheet.createRow(i);
with the following code
Row row = sheet.getRow(i);
if (row == null) row = sheet.createRow(i);
where new row is created only if it does not already exist!
And you're done, it works like a charm!

Internal links are not working on merged PDF files

I am currently modifying the logic for generating a PDF report, using itext package (itext-2.1.7.jar). The report is generated first, then - table of contents (TOC) and then TOC is inserted into the report file, using PdfStamper and it's method - replacePage:
PdfStamper stamper = new PdfStamper(new PdfReader(finalFile.getAbsolutePath()),
new FileOutputStream(reportFile));
stamper.replacePage(new PdfReader(tocFile.getAbsolutePath()), 1, 2);
However, I wanted TOC to also have internal links to point to the right chapter. Using replacePage() method, unfortunately, removes all links and annotations, so I tried another way. I've used a method I've found to merge the report file and the TOC file. It did the trick, meaning that the links were now preserved, but they don't seem to work, the user can click them, but nothing happens. I've placed internal links on other places in the report file, for testing purposes, and they seem to work, but they don't work when placed on the actual TOC. TOC is generated separately, here's how I've created the links (addLeadingDots is a local method, not pertinent to the problem):
Chunk anchor = new Chunk(idx + ". " + chapterName + getLeadingDots(chapterName, pageNumber) + " " + pageNumber, MainReport.FONT12);
String anchorLocation = idx+chapterName.toUpperCase().replaceAll("\\s","");
anchor.setLocalGoto(anchorLocation);
line = new Paragraph();
line.add(anchor);
line.setLeading(6);
table.addCell(line);
And this is how I've created anchor destinations on the chapters in the report file:
Chunk target = new Chunk(title.toUpperCase(), font);
String anchorDestination = title.toUpperCase().replace(".", "").replaceAll("\\s","");
target.setLocalDestination(anchorDestination);
Paragraph p = new Paragraph(target);
p.setAlignment(Paragraph.ALIGN_CENTER);
doc.add(p);
Finally, here's the method that supposed to merge report file and the TOC:
public static void mergePDFs(String originalFilePath, String fileToInsertPath, String outputFile, int location) {
PdfReader originalFileReader = null;
try {
originalFileReader = new PdfReader(originalFilePath);
} catch (IOException ex) {
System.out.println("ITextHelper.addPDFToPDF(): can't read original file: " + ex);
}
PdfReader fileToAddReader = null;
try {
fileToAddReader = new PdfReader(fileToInsertPath);
} catch (IOException ex) {
System.out.println("ITextHelper.addPDFToPDF(): can't read fileToInsert: " + ex);
}
if (originalFileReader != null && fileToAddReader != null) {
int numberOfOriginalPages = originalFileReader.getNumberOfPages();
Document document = new Document();
PdfCopy copy = null;
try {
copy = new PdfCopy(document, new FileOutputStream(outputFile));
document.open();
for (int i = 1; i <= numberOfOriginalPages; i++) {
if (i == location) {
for (int j = 1; j <= fileToAddReader.getNumberOfPages(); j++) {
copy.addPage(copy.getImportedPage(fileToAddReader, j));
}
}
copy.addPage(copy.getImportedPage(originalFileReader, i));
}
document.close();
} catch (DocumentException | FileNotFoundException ex) {
m_logger.error("ITextHelper.addPDFToPDF(): can't read output location: " + ex);
} catch (IOException ex) {
m_logger.error(Level.SEVERE, ex);
}
}
}
So, the main question is, what happens to the links, after both pdf documents are merged and how to make them work? I'm not too experienced with itext, so any help is appreciated.
Thanks for your help

How to getValueAt(int ,int) Listbox on zkoss like JTable in Swing

I want to export data from listbox to excel file,but my problem is How to do getValueAt(int,int) in zkoss like the following code.
int j = start;
for (int i = 0; i < model.getRowCount(); i++) {
for (j = start; j < col; j++) {
Object row2=model.getValueAt(i,j);
String str = (row2 == null ? "" : row2.toString());
//INI untuk memulai write ke file dari kolom ke berapa dan row ke berapa
Label row = new Label(j, i +1,str);
//INI untuk auto size cellnya
for(int x=0;x<model.getColumnCount();x++){
sheet1.setColumnView(x,30);
}
row.setCellFormat(formatRow);
sheet1.addCell(row);
}
}
Please help.
Well, actually this could be a lot easier then you think.
There is a project called ZK Exporter.
The following code (MVVM) is all you need to do when using this project :
#Command
public void exportListboxToExcel(#BindingParam("ref") Listbox listbox) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ExcelExporter exporter = new ExcelExporter();
exporter.export(listbox, out);
AMedia amedia = new AMedia("FirstReport.xlsx", "xls", "application/file", out.toByteArray());
Filedownload.save(amedia);
out.close();
}
If you want to read more about it, there is a complete small talk about it.
I personally did some changes on the awesome project, if you need them just ask it.
Mine changes are :
Listcell with multiple labels export now also, the original project get blanks.
checkboxes also exports to value TRUE/FALSE, original project get blanks.

Fitting a JTable in an iText PDF Document

I have a JTable that has four columns. I am using iText libraries to print PDF documents with data from the JTable. The problem is that the JTable is not showing properly in the PDF. I have searched on Google and came across the same situation here. The code is similar to mine as well as the output. I have also tried this example using Templates, however, the result is not changing.
How do we solve this? Please assist. If the codes are necessary, i will post but they are too many classes -i am working on a big application. The concept I would want is to make the JTable fit on the document.
After a long struggle, I managed to make it as shown below. In case someone encounters this, here is the idea that saved me:
public void actionPerformed(ActionEvent e) {
try {
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream("table.pdf"));
doc.open();
PdfPTable pdfTable = new PdfPTable(table.getColumnCount());
//adding table headers
for (int i = 0; i < table.getColumnCount(); i++) {
pdfTable.addCell(table.getColumnName(i));
}
//extracting data from the JTable and inserting it to PdfPTable
for (int rows = 0; rows < table.getRowCount() - 1; rows++) {
for (int cols = 0; cols < table.getColumnCount(); cols++) {
pdfTable.addCell(table.getModel().getValueAt(rows, cols).toString());
}
}
doc.add(pdfTable);
doc.close();
System.out.println("done");
} catch (DocumentException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
};

how to make my JTable refresh after adding a new row

After I add a new row to a JTable. The information wrote goes to the txt file, but my JTable doesn't shows the last raw. But if I close the program, and run it again, the information it's in the table. So, is there a way to refresh the data in the JTable without closing the application and running it again?
String[] columns = {"nume", "compozitie", "indicatii", "contraindicatii", "administrare", "pret", "compensabil", "stoc"};
Object[][] data = null;
try {
File file = new File("medicamente.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
data = new Object[100][];
String line;
int numLines = 0;
while ((line = bufferedReader.readLine()) != null) {
data[numLines] = line.split(",");
numLines++;
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
TableModel model = new DefaultTableModel(data, columns) {
#Override
public Class getColumnClass(int column) {
Class returnValue;
if ((column >= 0) && (column < getColumnCount())) {
returnValue = getValueAt(0, column).getClass();
} else {
returnValue = Object.class;
}
return returnValue;
}
};
JTable table = new JTable(model) {
public boolean isCellEditable(int row, int column) {
return false;
}
};
final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(1000, 500));
mainPanel.add(scrollPane);
scrollPane.setBounds(0, 240, 995, 510);
final JTextField filterText = new JTextField(null);
mainPanel.add(filterText);
filterText.setBounds(0, 750, 850, 25);
JButton button = new JButton("Filter");
mainPanel.add(button);
button.setBounds(850, 750, 150, 25);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = filterText.getText();
if (text.length() == 0) {
sorter.setRowFilter(null);
// model.fireTableDataChanged();
} else {
sorter.setRowFilter(RowFilter.regexFilter(text));
}
}
});
It looks like what you think is that when the file updates, so should the JTable. It doesn't work like that. What you need to do is add a row to the TableModel. A disadvantage in your case is this
TableModel model = new DefaultTableModel( data, columns)
You're using the TableModel interface, which has very limited methods you can use. Instead do this
DefaultTableModel model = new DefaultTableModel( data, columns)
Then you can use one of these methods from DefaultTableModel
public void addRow(Object[] rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
public void addRow(Vector rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
So when you want to add a row, you can gather your data into an array, addRow(..) then the table will get automatically update for you.
Object[] row = { data1, data2, data2, data4, data5 };
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(row);
Also it looks to me like your JTable is locally scoped. You may want to give it a global, class member scope, so you can access it from where ever you need to.
you must add your data to the model of jtable and then add the model to jtable and it will be refreshed , but before that you have to define a model .
Use this code.
private void resetListData() throws ClassNotFoundException, SQLException
{
Connection cne = null;
try {
// create connection in this line as per your database like I used sqlite. so my connection string is as follow
Class.forName("org.sqlite.JDBC");
cne = DriverManager.getConnection("jdbc:sqlite:table.sqlite");
cne.setAutoCommit(false);
PreparedStatement psd = (PreparedStatement) cne.prepareStatement("Select * from table");
psd.execute();
ResultSet r = psd.getResultSet();
ResultSetMetaData rsmd = r.getMetaData();
int count = rsmd.getColumnCount();
String[] meta = new String[count];
for (int i = 0; i < count; i++)
{
String name = rsmd.getColumnName(i + 1);
meta[i] = name;
//System.out.println(name);
}
model = new DefaultTableModel(new Object[][]{}, new String[]{"name", "address"});
jTable1.setModel(model);
while (r.next())
{
Object[] row = new Object[count];
for (int i = 1; i <= count; ++i)
{
row[i - 1] = r.getString(i); // Or even rs.getObject()
}
model.addRow(row);
}
cne.close();
} catch (ClassNotFoundException | SQLException e) {
}
}
create connection and query as per your need.. my code add one row at the end of Jtable. My code directly working with your database..
Thanks..
by the way why you're using TableRowSorter in your code , why you don't use just the jtable and defaultmodel directly
I recently had the same problem and the solution was to call
model.fireTableDataChanged();
right after adding the new row to the model.
My issue was the following: I had a table on which I allowed sorting. Without clicking the column headers so that the rows would sort accordingly, I was able to add data to the model and see the changes in the table by calling table.revalidate(); However, if, at any time, I clicked the column headers, any row added afterwards wouldn't be shown, although the model data was updating properly. By only calling model.fireTableDataChanged(); after adding the data to the model, it works as a charm.

Categories

Resources