Código de Java - Imprimir JTable directamente en Java

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

Imprimir JTable directamente en Javagráfica de visualizaciones


Java

Publicado el 18 de Enero del 2016 por Julio (12 códigos)
17.278 visualizaciones desde el 18 de Enero del 2016
Vamos con otro ejemplo sencillo con Java Swing en este caso vamos a ver como podemos imprimir automáticamente y de forma sencilla el contenido de cualquier JTable directamente por la impresora del sistema utilizando el método de JTable print.

JFrameJTablePrintExample-Imprimir-JTable-directamente-en-Java

Para poder utilizar este método con cualquier JTable voy a crear un método donde pasaré por parámetros los elementos principales que me interesan: public void utilJTablePrint(JTable jTable, String header, String footer, boolean showPrintDialog).

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
/**
 * Standard method to print a JTable to the printer directly..
 * Método estándar para imprimir un JTable por la impresora directamente.
 * <h3>Example (Ejemplo)</h3>
 * <pre>
 *      utilJTablePrint(jTable2, getTitle(), "Código Xules", true);
 * </pre>
 *
 * @param jTable <code>JTable</code> 
 *      the JTable we are going to extract to excel 
 *      El Jtable que vamos a extraer a excel.
 * @param header <code>String</code>
 *      Header to print in the document.
 *      Cabecera que imprimiremos en el documento.
 * @param footer <code>String</code>
 *      Footer to print in the document.
 *      Pie de página que imprimiremos en el documento.
 * @param showPrintDialog  <code>boolean</code>
 *      To show or not the print dialog.
 *      Mostramos o no el diálogo de impresión.
 */
public void utilJTablePrint(JTable jTable, String header, String footer, boolean showPrintDialog){
    boolean fitWidth = true;
    boolean interactive = true;
    // We define the print mode (Definimos el modo de impresión)
    JTable.PrintMode mode = fitWidth ? JTable.PrintMode.FIT_WIDTH : JTable.PrintMode.NORMAL;
    try {
        // Print the table (Imprimo la tabla)             
        boolean complete = jTable.print(mode,
                new MessageFormat(header),
                new MessageFormat(footer),
                showPrintDialog,
                null,
                interactive);
        if (complete) {
            // Mostramos el mensaje de impresión existosa
            JOptionPane.showMessageDialog(jTable,
                    "Print complete (Impresión completa)",
                    "Print result (Resultado de la impresión)",
                    JOptionPane.INFORMATION_MESSAGE);
        } else {
            // Mostramos un mensaje indicando que la impresión fue cancelada                 
            JOptionPane.showMessageDialog(jTable,
                    "Print canceled (Impresión cancelada)",
                    "Print result (Resultado de la impresión)",
                    JOptionPane.WARNING_MESSAGE);
        }
    } catch (PrinterException pe) {
        JOptionPane.showMessageDialog(jTable,
                "Print fail (Fallo de impresión): " + pe.getMessage(),
                "Print result (Resultado de la impresión)",
                JOptionPane.ERROR_MESSAGE);
    }
}

Espero que te sea útil.

Requerimientos

El objetivo de este ejemplo es la impresión directa de un JTable desde Java Swing si necesitas una explicación de como crear este ejemplo usando Netbeans tienes más detalles aquí: http://codigoxules.org/imprimir-jtable-directamente-java-java-swing/

1.0
estrellaestrellaestrellaestrellaestrella(7)

Publicado el 18 de Enero del 2016gráfica de visualizaciones de la versión: 1.0
17.279 visualizaciones desde el 18 de Enero del 2016
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

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
package org.xulescode.swing;
 
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.print.PrinterException;
import java.text.MessageFormat;
import javax.swing.JOptionPane;
import javax.swing.JTable;
 
/**
 * We created a simple table with data to show as directly print the contents 
 * of the table by printer.
 * Creamos una tabla con datos sencilla para mostrar como imprimir directamente 
 * el contenido de la tabla por impresora.
 * 
 * @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 JFrameJTablePrintExample extends javax.swing.JFrame {
 
    /**
     * Creates new form JFrameJTablePrintExample.
     * Creamos un nuevo form JFrameJTablePrintExample.
     */
    public JFrameJTablePrintExample() {
        initComponents();
        setLocationCenter();
        setVisible(true);
    }
    /**
     * 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);
    }
 
    /**
     * Standard method to print a JTable to the printer directly..
     * Método estándar para imprimir un JTable por la impresora directamente.
     * <h3>Example (Ejemplo)</h3>
     * <pre>
     *      utilJTablePrint(jTable2, getTitle(), "Código Xules", true);
     * </pre>
     *
     * @param jTable <code>JTable</code> 
     *      the JTable we are going to extract to excel 
     *      El Jtable que vamos a extraer a excel.
     * @param header <code>String</code>
     *      Header to print in the document.
     *      Cabecera que imprimiremos en el documento.
     * @param footer <code>String</code>
     *      Footer to print in the document.
     *      Pie de página que imprimiremos en el documento.
     * @param showPrintDialog  <code>boolean</code>
     *      To show or not the print dialog.
     *      Mostramos o no el diálogo de impresión.
     */
    public void utilJTablePrint(JTable jTable, String header, String footer, boolean showPrintDialog){
        boolean fitWidth = true;
        boolean interactive = true;
        // We define the print mode (Definimos el modo de impresión)
        JTable.PrintMode mode = fitWidth ? JTable.PrintMode.FIT_WIDTH : JTable.PrintMode.NORMAL;
        try {
            // Print the table (Imprimo la tabla)             
            boolean complete = jTable.print(mode,
                    new MessageFormat(header),
                    new MessageFormat(footer),
                    showPrintDialog,
                    null,
                    interactive);
            if (complete) {
                // Mostramos el mensaje de impresión existosa
                JOptionPane.showMessageDialog(jTable,
                        "Print complete (Impresión completa)",
                        "Print result (Resultado de la impresión)",
                        JOptionPane.INFORMATION_MESSAGE);
            } else {
                // Mostramos un mensaje indicando que la impresión fue cancelada                 
                JOptionPane.showMessageDialog(jTable,
                        "Print canceled (Impresión cancelada)",
                        "Print result (Resultado de la impresión)",
                        JOptionPane.WARNING_MESSAGE);
            }
        } catch (PrinterException pe) {
            JOptionPane.showMessageDialog(jTable,
                    "Print fail (Fallo de impresión): " + pe.getMessage(),
                    "Print result (Resultado de la impresión)",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
    /**
     * 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() {
 
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("IMPRESIÓN DE TABLA POR IMPRESORA");
 
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Imprimimos la tabla por la impresora"));
 
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"7890", "José", "Novoa", "45866321d", "Encrucijada 2, 2º E Madrid"},
                {"5896", "Jan", "Ruiz", "78451245d", "Etiopía 3, 4ºW , Vigo"},
                {"2569", "Xian", "Iconic", "89562323e", "Salamanca 45, 3ºS, Santiago"},
                {"2548", "Pep", "Mac", "85963966e", "Barcelona, nº123, 3ºS, Girona"}
            },
            new String [] {
                "CLIENTE", "NOMBRE", "APELLIDOS", "DNI", "DIRECCIÓN"
            }
        ));
        jScrollPane1.setViewportView(jTable1);
 
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 415, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
 
        jButton1.setText("SALIR");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
 
        jButton2.setText("IMPRIMIR POR IMPRESORA");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(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()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(84, 84, 84)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 81, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(89, 89, 89))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(18, Short.MAX_VALUE))
        );
 
        pack();
    }// </editor-fold>                        
 
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        utilJTablePrint(jTable1, getTitle(), "Código Xules", true);
    }
 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        dispose();
    }
 
    /**
     * @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(JFrameJTablePrintExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrameJTablePrintExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrameJTablePrintExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrameJTablePrintExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JFrameJTablePrintExample().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration                   
}



Comentarios sobre la versión: 1.0 (7)

Imágen de perfil
21 de Enero del 2016
estrellaestrellaestrellaestrellaestrella
excelente amigo
Responder
an dres
10 de Junio del 2016
estrellaestrellaestrellaestrellaestrella
grande ¡¡¡¡¡


muchas gracias
Responder
jmnieto
23 de Febrero del 2017
estrellaestrellaestrellaestrellaestrella
Buenos días.
He realizado lo que indicas y funciona perfectamente, el problema que me da es que al sacar la jtable en formato PDF, las columnas tienen la misma longitud y no se ven los datos correctamente.

¿Cómo se puede hacer para que se respete la anchura de la columna?

Gracias.
Responder
13 de Abril del 2018
estrellaestrellaestrellaestrellaestrella
Disculpen como podría imprimir dos tables seguidos en una misma hoja
Responder
Javier
19 de Mayo del 2018
estrellaestrellaestrellaestrellaestrella
La impresion me funciona con tablas medianas, pero cuando intento imprimir tablas con mas de 30.000 registros no salen todas las hojas y el consumo de ram se dispara, como podria solucionar esto? agradezco su atencion
Responder
Juan
9 de Abril del 2019
estrellaestrellaestrellaestrellaestrella
Excelente!, me funciono a la primera y me imprime la tabla tal cual se ve en pantalla. Muchas gracias, saludos!!
Responder
Imágen de perfil
11 de Abril del 2019
estrellaestrellaestrellaestrellaestrella
Me alegro que te sea útil, un saludo
Responder

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/s3412