Código de Java - Java JTable importar ficheros con Java I/O y exportar a PDF con iText

Imágen de perfil
Val: 42
Ha disminuido su posición en 2 puestos en Java (en relación al último mes)
Gráfica de Java

Java JTable importar ficheros con Java I/O y exportar a PDF con iTextgráfica de visualizaciones


Java

Publicado el 3 de Marzo del 2016 por Julio (12 códigos)
8.676 visualizaciones desde el 3 de Marzo del 2016
Este es un código donde verás como utilizar b]Java I/O[/b] para cargar los ficheros en un JTable y como exportar el contenido de un JTable a PDF con iText.

Utilizamos Java I/O que agrupa las librerías para manejar ficheros, entrada y salida, lectura de directorio y cargar el JTable
ver como exportar el contenido del JTable a PDF con un método estándar que nos valdrá para cualquier javax.swing.JTable usando iText PDF.

Java-JTable-importar-contenido-carpeta-y-exportar-a-PDF-con-iText

Definimos nuestra clase con las siguientes condiciones:

Constructor: pasamos por parámetros la carpeta que queremos leer y cargar en un javax.swing.JTable, donde las columnas serán el nombre del fichero y varios datos.
Leer el directorio (carpeta) : utilizamos Java I/O (http://codigoxules.org/java/java-io/)para leer el directorio y obtener la información que cargamos en la tabla.
DefaultTableModel: el modelo de datos de la tabla que será fijo con las columnas: NOMBRE, EXTENSIÓN, LEÍBLE, FECHA MODIFICACIÓN, TRASPASAR, TAMAÑO y NOMBRE COMPLETO.
Carga de los ficheros: todas las acciones necesarias para cargar el directorio con los ficheros los agrupamos en un método, así si queremos añadir un botón de actualización, solo tenemos que llamar a este método.
Exportar a PDF: crearemos un botón para ejecutar la acción de exportación a iText PDF, para ello crearemos un método genérico que se pueda reutilizar con cualquier javax.swing.JTable, para obtener información más detallas puedes leer el artículo: Java iText PDF – Creando un pdf en Java con iText (http://codigoxules.org/java-itext-pdf-creando-pdf-java-itext/).


Espero que te haya resultado útil.

Requerimientos

Este código formar parte de los ejemplos sobre el uso de Java Swing las explicaciones las puedes encontrar en el código y con más detalle en Java JTable importar contenido carpeta y exportar a PDF (http://codigoxules.org/java-jtable-importar-contenido-carpeta-exportar-pdf/)
Tecnologías utilizadas

1.0

Publicado el 3 de Marzo del 2016gráfica de visualizaciones de la versión: 1.0
8.677 visualizaciones desde el 3 de Marzo del 2016
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

JFrameJTableFilesToPdf-02-Listado-de-Ficheros
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
package org.xulescode.swing;
 
import com.itextpdf.text.Anchor;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
 
/**
 * Load files a route and simulate processing, in this example, 
 * we seek simply to explain the simple creation of a table (JTable) that 
 * can be reused by adding capabilities to generate a PDF.
 * Cargamos los ficheros de una ruta y simulamos su procesamiento, en este ejemplo,
 * buscamos simplemente explicar la creación sencilla de una tabla (JTable) que podemos reutilizar 
 * añadiéndole las capacidades de generar un PDF.
 * 
 * @author xules You can follow me on my website http://www.codigoxules.org/en
 * Puedes seguirme en mi web http://www.codigoxules.org
 */
public class JFrameJTableFilesToPdf extends javax.swing.JFrame {
 
    // Table model variable (variable para el modelo de datos).
    private DefaultTableModel tableModelFiles;
 
    private String pathFilesImport;
    private String fileExtension;
 
    private static final Font categoryFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,  Font.BOLD);
    private static final Font subCategoryFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,  Font.BOLD);
    private static final Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,  Font.NORMAL, BaseColor.RED);
    private static final Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
 
    /**
     * Creates new form JFrameJTableFilesToPdf.
     * Creamos un nuevo form JFrameJTableFilesToPdf.
     * @param path <code>String</code> the path where we are going to read the files.
     * La ruta de la que vamos a leer los ficheros.
     */
    public JFrameJTableFilesToPdf(String path) {
        // Components loading (Carga de componentes)
        initComponents();
        pathFilesImport = path;
        initJTable();
        // Load the files in the table (Cargamos los ficheros en la tabla).
        loadTableModelFiles(tableModelFiles,
                pathFilesImport, null,
                null, // extesionFile,
                pathFilesImport,
                System.out);
        setLocationCenter();
        setVisible(true);
    }
 
    /**
     * Helper method which define the presentation of the table.
     * Método auxiliar donde definimos la presentación de la tabla. 
     */
    private void initJTable() {
        jTextFieldRuta.setText(pathFilesImport);
        Object[] newObjectItems = initJTableFiles(jTableFicheros, jScrollPaneFicheros, tableModelFiles);
        tableModelFiles = (DefaultTableModel) newObjectItems[2];
        jTableFicheros = (JTable) newObjectItems[0];
        jScrollPaneFicheros = (JScrollPane) newObjectItems[1];
 
    }
 
    /**
     * We create a specific JTable with parameters passed to the method.
     * Creamos un JTable específico con los parámetros que se pasan en el método.
     * @param jTable <code>JTable</code> tabla del JFrame que volvemos a definir en esta clase.
     * @param jScrollPane <code>JScrollPane</code> pasamos de nuevo el JScrollPane para vincularlo de nuevo con el nuevo JTable.
     * @param tableModel <code>tableModel</code> modelo nuevo de tabla que definimos con los parámetros que pasamos.          
     * @return <code>Object[]</code> returns an array with the new values of jTable, jScrollPane and tableModel (devuelve una array con los nuevos valores
     * de jTable, jScrollPane y tableModel).
     */
    private Object[] initJTableFiles(JTable jTable, JScrollPane jScrollPane, DefaultTableModel tableModel) {
        Object[] object = null;
        // We define te (Definimos el modelo de la tabla).
        tableModel = new DefaultTableModel(
                new Object[][]{},
                new String[]{
                    "NOMBRE", "EXTENSIÓN", "LEIBLE", "FECHA MODIFICACIÓN",
                    "TRASPASAR", "TAMAÑO", "NOMBRE COMPLETO"
                }
        ) {
            // Data types of the columns (Tipos de datos de las columnas).
            Class[] types = new Class[]{
                java.lang.String.class, java.lang.String.class, java.lang.Boolean.class,
                java.util.Date.class, java.lang.Boolean.class, java.lang.String.class, java.lang.String.class,};
            // Editables columns (Columnas editables).
            boolean[] canEdit = new boolean[]{
                false, false, false, false, false, true, false, false
            };
            @Override
            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }
            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        };
        jTable = new JTable();
        jTable.setModel(tableModel);
        jScrollPane.setViewportView(jTable);
        // We define the width of the columns (Definimos el ancho de las columnas).
        if (jTable.getColumnModel().getColumnCount() > 0) {
            jTable.getColumnModel().getColumn(0).setPreferredWidth(120);
            jTable.getColumnModel().getColumn(1).setPreferredWidth(60);
            jTable.getColumnModel().getColumn(2).setPreferredWidth(60);
            jTable.getColumnModel().getColumn(3).setPreferredWidth(100);
            jTable.getColumnModel().getColumn(4).setPreferredWidth(70);
            jTable.getColumnModel().getColumn(5).setPreferredWidth(60);
            jTable.getColumnModel().getColumn(6).setPreferredWidth(500);
        }
        // Columns auto sort (Ordenación automática de las columnas).
        jTable.setAutoCreateRowSorter(true);
        object = new Object[]{jTable, jScrollPane, tableModel};
        return object;
    }
 
    /**
     * Read the directory as directed by the parameters and load the table.
     * Leemos el directorio según las indicaciones de los parámetros y cargamos la tabla.
     * @param tableModel <code>tableModel</code> modelo nuevo de tabla que definimos con los parámetros que pasamos.     
     * @param filesPath <code>String</code> the path where we are going to read the files (La ruta de la que vamos a leer los ficheros).
     * @param filesDir <code>String</code> folder selected to read (carpeta seleccionada para leer).
     * @param extesionFile <code>String</code> filtering file extension (filtrado para extensión de archivos).
     * @param folder <code>String</code> path where we are going to read the files. Ruta donde vamos a leer los ficheros.
     * @param output <code>PrintStream</code> pass the PrintStream output (pasamos el PrintStream de salida). 
     * @return <code>boolean</code> we return true if the directory that we pass
     * for read exists. Devolvemos true si existe el directorio que se pasa para leer.
     */
    public boolean loadTableModelFiles(DefaultTableModel tableModel,
            String filesPath,  File filesDir,
            String extesionFile,
            String folder, PrintStream output) {
        boolean resultado;
        int row = 0;
        // Folder to read: folderFile (Fichero para leer).
        File folderFile = new File(folder);
        /*
            Then we read all the folder, the implementation 
            of filters extesionFile FilesDir and can be incorporated easily here.
            A continuación, leemos toda la carpeta, la implementación 
            de los filtros filesDir y extesionFile se puede incorporar aquí fácilmente.
         */
        if ((resultado = folderFile.exists())) {
            File[] files = folderFile.listFiles();
            for (File file : files) {
                boolean isFolder = file.isDirectory();
                if ((!isFolder)) {
                    output.println((isFolder ? "FOLDER: " : "  FILE: ") + file.getName());
                    double fileBytes = file.length();
                    double fileKiloBytes = (fileBytes / 1024);
                    double fileMegaBytes = (fileKiloBytes / 1024);
                    // Add rows to the TableModel (Añadimos filas al tableModel).
                    tableModel.insertRow(row++,
                            new Object[]{
                                file.getName(),                     // Name (Nombre)
                                getFileExtension(file.getName()),   // Extension (Extensión)                                
                                file.canRead(),                             // Readable (Leible)                 
                                new java.util.Date(file.lastModified()),    // Modify date (Fecha modificación)
                                false,                                      // Transfer (Traspasar)
                                fileKiloBytes + " KB",  // File Size (Tamaño del fichero)
                                file.getAbsolutePath()  // Absolute Path (Ruta del fichero completa)
                            });
                }
            }
        }
        return resultado;
    }
    /**
     * Returns the extension of a file that we pass as a parameter.
     * Devuelve la extensión de un archivo que se pasa como parámetro.
     * @param fileName <code>String</code> the file name (el nombre del fichero).
     * @return <code>String</code> the extension of the file name (la extensión del nombre del fichero).
     */
    public String getFileExtension(String fileName) {
        try {
            fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
        } catch (Exception e) {
            fileExtension = "UNKNOW";
        }
        return fileExtension;
    }
    /**
     * Returns the path to load the files
     * Devuelve la ruta de la carga de ficheros.
     * @return <code>String</code> the path to load the files (la ruta the la carga de ficheros).
     */
    public String getPathFilesImport() {
        return pathFilesImport;
    }
    /**
     * Stores the path to load de files.
     * Almacena la ruta de la carga de ficheros.
     * @param pathFilesImport <code>String</code> the path to load the files (la ruta the la carga de ficheros).
     */
    public void setPathFilesImport(String pathFilesImport) {
        this.pathFilesImport = pathFilesImport;
    }
 
 
    /**
     * Explanation of the method by which we read the JTable we pass as
     * parameter, and where we copy its content in a PDF passed 
     * as a parameter.
     * Método con el que leemos cualquier JTable que pasamos como
     * parámetro, y donde copiamos su contenido en un PDF que se pasa 
     * como parámetro. 
     *
     * @param jTable <code>JTable</code> 
     *      the JTable we are going to extract to excel 
     *      El Jtable que vamos a extraer a excel.
     * @param pdfNewFile <code>String</code> 
     *      pdf File we are going to write. 
     *      Fichero pdf en el que vamos a escribir. 
     * @param title <code>String</code> 
     *      title
     *      Título 
     */
    public void utilJTableToPdf(JTable jTable, File pdfNewFile, String title){
        try {
            // We create the document and set the file name.        
            // Creamos el documento e indicamos el nombre del fichero.
            Document document = new Document();
            try {
                PdfWriter.getInstance(document, new FileOutputStream(pdfNewFile));
            } catch (FileNotFoundException fileNotFoundException) {
                System.out.println("No such file was found to generate the PDF (No se encontró el fichero para generar el pdf)" + fileNotFoundException);
            }
            document.open();
            // We add metadata to PDF
            // Añadimos los metadatos del PDF
            document.addTitle("Table export to PDF (Exportamos la tabla a PDF)");
            document.addSubject("Using iText (usando iText)");
            document.addKeywords("Java, PDF, iText");
            document.addAuthor("Código Xules");
            document.addCreator("Código Xules");
 
            // First page (Primera página)
            Anchor anchor = new Anchor("Table export to PDF (Exportamos la tabla a PDF)", categoryFont);
            anchor.setName("Table export to PDF (Exportamos la tabla a PDF)");
 
            // Second parameter is the number of the chapter (El segundo parámetro es el número del capítulo).
            Chapter catPart = new Chapter(new Paragraph(anchor), 1);
 
            Paragraph subPara = new Paragraph("Do it by Xules (Realizado por Xules)", subCategoryFont);
            Section subCatPart = catPart.addSection(subPara);
            subCatPart.add(new Paragraph("This is a simple example (Este es un ejemplo sencillo)"));
 
            // Create the table (Creamos la tabla)
            PdfPTable table = new PdfPTable(jTable.getColumnCount());
 
            // Now we fill the rows of the PdfPTable (Ahora llenamos las filas de PdfPTable)
            PdfPCell columnHeader;
            // Fill table columns header 
            // Rellenamos las cabeceras de las columnas de la tabla.                
            for (int column = 0; column < jTable.getColumnCount(); column++) {
                columnHeader = new PdfPCell(new Phrase(jTable.getColumnName(column)));
                columnHeader.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(columnHeader);
            }
            table.setHeaderRows(1);
            // Fill table rows (rellenamos las filas de la tabla).                
            for (int row = 0; row < jTable.getRowCount(); row++) {
                for (int column = 0; column < jTable.getColumnCount(); column++) {
                    table.addCell(jTable.getValueAt(row, column).toString());
                }
            }
            subCatPart.add(table);
 
            document.add(catPart);
 
            document.close();
            JOptionPane.showMessageDialog(this.jPanelFicheros, "Your PDF file has been generated!(¡Se ha generado tu hoja PDF!)",
                    "RESULTADO", JOptionPane.INFORMATION_MESSAGE);
        } catch (DocumentException documentException) {
            System.out.println("The file not exists (Se ha producido un error al generar un documento): " + documentException);
            JOptionPane.showMessageDialog(this.jPanelFicheros, "The file not exists (Se ha producido un error al generar un documento): " + documentException,
                    "ERROR", JOptionPane.ERROR_MESSAGE);
        }
 
    }
    /**
     * Set the JFrame in the center of the screen. Colocamos nuestro JFrame en
     * el centro de la pantalla.
     */
    public void setLocationCenter() {
        setLocationMove(0, 0);
    }
 
    /**
     * Place the JFrame with the parameters by moving the component relative to
     * the center of the screen. Colocamos el JFrame con los parámetros
     * desplazando el componente respecto al centro de la pantalla.
     *
     * @param moveWidth int positive or negative offset width (desplazamiente de
     * width positivo o negativo).
     * @param moveHeight int Positive or negative offset height (desplazamiento
     * de height positivo o negativo).
     */
    public void setLocationMove(int moveWidth, int moveHeight) {
        // Obtenemos el tamaño de la pantalla.
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        // Obtenemos el tamaño de nuestro frame.
        Dimension frameSize = this.getSize();
        frameSize.width = frameSize.width > screenSize.width ? screenSize.width : frameSize.width;
        frameSize.height = frameSize.height > screenSize.height ? screenSize.height : frameSize.height;
        // We define the location. Definimos la localización.
        setLocation((screenSize.width - frameSize.width) / 2 + moveWidth, (screenSize.height - frameSize.height) / 2 + moveHeight);
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
 
        jPanelFicheros = new javax.swing.JPanel();
        jLabelRuta = new javax.swing.JLabel();
        jTextFieldRuta = new javax.swing.JTextField();
        jScrollPaneFicheros = new javax.swing.JScrollPane();
        jTableFicheros = new javax.swing.JTable();
        jButtonViewPdf = new javax.swing.JButton();
        jButtonSalir = new javax.swing.JButton();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("SELECCIÓN DE FICHEROS PARA PROCESAR");
 
        jPanelFicheros.setBorder(javax.swing.BorderFactory.createTitledBorder("Ficheros para procesar"));
 
        jLabelRuta.setFont(new java.awt.Font("Ubuntu", 0, 12)); // NOI18N
        jLabelRuta.setText("Ruta seleccionada:");
 
        jTextFieldRuta.setEditable(false);
        jTextFieldRuta.setFont(new java.awt.Font("Ubuntu", 0, 12)); // NOI18N
        jTextFieldRuta.setText("Se indicará la ruta utilizada");
        jTextFieldRuta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldRutaActionPerformed(evt);
            }
        });
 
        jScrollPaneFicheros.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jScrollPaneFicheros.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
 
        jTableFicheros.setAutoCreateRowSorter(true);
        jTableFicheros.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPaneFicheros.setViewportView(jTableFicheros);
 
        javax.swing.GroupLayout jPanelFicherosLayout = new javax.swing.GroupLayout(jPanelFicheros);
        jPanelFicheros.setLayout(jPanelFicherosLayout);
        jPanelFicherosLayout.setHorizontalGroup(
            jPanelFicherosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelFicherosLayout.createSequentialGroup()
                .addComponent(jLabelRuta, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jTextFieldRuta, javax.swing.GroupLayout.PREFERRED_SIZE, 524, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(22, 22, 22))
            .addGroup(jPanelFicherosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanelFicherosLayout.createSequentialGroup()
                    .addComponent(jScrollPaneFicheros, javax.swing.GroupLayout.PREFERRED_SIZE, 662, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 21, Short.MAX_VALUE)))
        );
        jPanelFicherosLayout.setVerticalGroup(
            jPanelFicherosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelFicherosLayout.createSequentialGroup()
                .addGroup(jPanelFicherosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelRuta, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldRuta, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(341, 341, 341))
            .addGroup(jPanelFicherosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelFicherosLayout.createSequentialGroup()
                    .addGap(0, 25, Short.MAX_VALUE)
                    .addComponent(jScrollPaneFicheros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
 
        jButtonViewPdf.setText("Generar PDF");
        jButtonViewPdf.setFocusable(false);
        jButtonViewPdf.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jButtonViewPdf.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonViewPdf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonViewPdfActionPerformed(evt);
            }
        });
 
        jButtonSalir.setText("SALIR");
        jButtonSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSalirActionPerformed(evt);
            }
        });
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(135, 135, 135)
                .addComponent(jButtonViewPdf, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 171, Short.MAX_VALUE)
                .addComponent(jButtonSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(136, 136, 136))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanelFicheros, javax.swing.GroupLayout.PREFERRED_SIZE, 682, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(493, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButtonSalir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonViewPdf))
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanelFicheros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(43, Short.MAX_VALUE)))
        );
 
        pack();
    }// </editor-fold>                        
 
    private void jTextFieldRutaActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }
    /**
     * Exit button.
     * Botón de salida.
     * @param evt button event (evento del botón).
     */
    private void jButtonSalirActionPerformed(java.awt.event.ActionEvent evt) {
        dispose();
    }
    /**
     * PDF generation (Generación del PDF)
     * @param evt button event (evento del botón).
     */
    private void jButtonViewPdfActionPerformed(java.awt.event.ActionEvent evt) {
        // PDF generation (Generación del PDF)
        utilJTableToPdf(jTableFicheros, new File("pdfJTable.pdf"), getTitle() + " (Código Xules)");
    }
 
 
    /**
     * Test our code.
     * Probamos nuestro código.
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrameJTableFilesToPdf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrameJTableFilesToPdf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrameJTableFilesToPdf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrameJTableFilesToPdf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JFrameJTableFilesToPdf("/home/xules/codigoxules").setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButtonSalir;
    private javax.swing.JButton jButtonViewPdf;
    private javax.swing.JLabel jLabelRuta;
    private javax.swing.JPanel jPanelFicheros;
    private javax.swing.JScrollPane jScrollPaneFicheros;
    private javax.swing.JTable jTableFicheros;
    private javax.swing.JTextField jTextFieldRuta;
    // End of variables declaration                   
}



Comentarios sobre la versión: 1.0 (0)


No hay comentarios
 

Comentar la versión: 1.0

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s3452