package org.xulescode.swing;
import java.awt.*;
import java.awt.print.PrinterException;
import java.io.*;
import java.sql.*;
import java.text.MessageFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* We create a table where we load an SQL query to PostgreSQL database,
* parameters defined by the column names, type and whether they are editable
* for presentation.
* Creamos una tabla donde cargamos una consulta SQL sobre la base de datos PostgreSQL,
* definimos por parámetros su presentación.
* <pre>
* SELECT idlanguage, namelanguage, isactive, languageiso, countrycode,
* isbaselanguage, issystemlanguage
* FROM cb_language;
* </pre>
*
* @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 JFrameJTableDatabaseToExcelExampleMas extends javax.swing.JFrame {
// Variable to manage database connection (variable para manejar la conexión a la base de datos).
private Connection connection = null;
// Table model variable (variable para el modelo de datos).
private DefaultTableModel tableModelQuery;
/**
* We create a constructor to load a SQL query by passing parameters which define the query,
* the column name, data type columns.
* Creamos un constructor para cargar una consulta SQL mediante el paso de
* parámetros donde definimos la consulta, los nombre de las columnas, el tipo de datos de las columnas
* @param query <code>String</code> we pass the query we want to load (pasamos la consulta que queremos a cargar).
* @param columns <code>String[]</code> we define the names of the columns (definimos los nombre de las columnas).
* @param types <code>Class[]</code> we define the data types of the columns (definimos el tipo de datos de las columnas.).
* @param editable <code>boolean[]</code> we define if columns are editable or not (definimos si las columnas son editables o no).
* @param columnsWidth <code>int[]</code> the width of each column to present in the table (el ancho de cada columna para presentar en la tabla).
*/
public JFrameJTableDatabaseToExcelExampleMas(String query, String[] columns, Class[] types, boolean[] editable, int[] columnsWidth) {
initComponents();
boolean testConnection = connectDatabase("192.168.0.26", "5432", "customerdb","xulescode", "xulescode");
if (testConnection){
cargaConsulta(query, columns, types, editable, columnsWidth);
setLocationCenter();
setVisible(true);
}else{
System.out.println("No se ha podido conectar con la base de datos.");
}
}
/**
* Method where we group all we need to load the table, this will allow us
* to reuse creating for example a button to reload the query.
* Método donde agrupamos todo lo que necesitamos para cargar la tabla, esto nos permitirá su reutilización
* creando por ejemplo un botón para recargar la consulta.
* @param query <code>String</code> we pass the query we want to load (pasamos la consulta que queremos a cargar).
* @param columns <code>String[]</code> we define the names of the columns (definimos los nombre de las columnas).
* @param types <code>Class[]</code> we define the data types of the columns (definimos el tipo de datos de las columnas.).
* @param editable <code>boolean[]</code> we define if columns are editable or not (definimos si las columnas son editables o no).
* @param columnsWidth <code>int[]</code> the width of each column to present in the table (el ancho de cada columna para presentar en la tabla).
*/
public void cargaConsulta(String query, String[] columns, Class[] types, boolean[] editable, int[] columnsWidth){
try {
// We define the data model table with the parameters.
// Definimos el modelo de datos de la tabla con los parámetros.
initJTable(columns, types, editable, columnsWidth);
// Execute the query using java.sql.Statement.
// Ejecutamos la consulta utilizando java.sql.Statement.
Statement statement = getConnection().createStatement();
ResultSet resultSet = statement.executeQuery(query);
int row = 0;
/*
If we get results we go through the java.sql.ResultSet to obtain
the data and load them into our model table.
Si obtenemos resultados recorremos el java.sql.ResultSet para
obtener los datos y cargarlos en nuestro modelo de tabla.
*/
while (resultSet.next()){
Object[] newRow = new Object[columns.length];
for (int i = 0; i < columns.length; i++) {
newRow[i] = resultSet.getObject(i + 1);
}
// We add the rows to our table.
// Vamos añadiendo las filas a nuestra tabla
tableModelQuery.insertRow(row++, newRow);
}
} catch (SQLException ex) {
Logger.getLogger(JFrameJTableDatabaseToExcelExampleMas.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Method to connect to the database by passing parameters.
* Método para establecer la conexión a la base de datos mediante el paso de parámetros.
*
* @param host <code>String</code> host name or ip. Nombre del host o ip.
* @param port <code>String</code> listening database port. Puerto en el que escucha la base de datos.
* @param database <code>String</code> database name for the connection. Nombre de la base de datos para la conexión.
* @param user <code>String</code> user name. Nombre de usuario.
* @param password <code>String</code> user password. Password del usuario.
*/
private boolean connectDatabase(String host, String port, String database,
String user, String password) {
String url = "";
try {
// We register the PostgreSQL driver
// Registramos el driver de PostgresSQL
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
System.out.println("Error al registrar el driver de PostgreSQL: " + ex);
}
url = "jdbc:postgresql://" + host + ":" + port + "/" + database;
// Database connect
// Conectamos con la base de datos
setConnection(DriverManager.getConnection(
url,
user, password));
boolean valid = connection.isValid(50000);
System.out.println(valid ? "TEST OK" : "TEST FAIL");
return valid;
} catch (java.sql.SQLException sqle) {
System.out.println("Error al conectar con la base de datos de PostgreSQL (" + url + "): " + sqle);
return false;
}
}
/**
* Helper method which define the presentation of the table.
* Método auxiliar donde definimos la presentación de la tabla.
* @param columns <code>String[]</code> we define the names of the columns (definimos los nombre de las columnas).
* @param types <code>Class[]</code> we define the data types of the columns (definimos el tipo de datos de las columnas.).
* @param editable <code>boolean[]</code> we define if columns are editable or not (definimos si las columnas son editables o no).
* @param columnsWidth <code>int[]</code> the width of each column to present in the table (el ancho de cada columna para presentar en la tabla).
*/
private void initJTable(String[] columns, Class[] types, boolean[] editable, int[] columnsWidth) {
Object[] newObjectItems = initJTableQuery(jTableQuery, jScrollPaneQuery, tableModelQuery, columns, types, editable, columnsWidth);
tableModelQuery = (DefaultTableModel) newObjectItems[2];
jTableQuery = (JTable) newObjectItems[0];
jScrollPaneQuery = (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.
* @param columns <code>String[]</code> we define the names of the columns (definimos los nombre de las columnas).
* @param types <code>Class[]</code> we define the data types of the columns (definimos el tipo de datos de las columnas.).
* @param editable <code>boolean[]</code> we define if columns are editable or not (definimos si las columnas son editables o no).
* @param columnsWidth <code>int[]</code> the width of each column to present in the table (el ancho de cada columna para presentar en la tabla).
* @return <code>Object[]</code> returns an array with the values of jTable, jScrollPane y tableModel ( devuelve una array con los nuevos valores
* de jTable, jScrollPane y tableModel).
*/
private Object[] initJTableQuery(JTable jTable, JScrollPane jScrollPane, DefaultTableModel tableModel,
String[] columns, Class[] types, boolean[] editable, int[] columnsWidth) {
Object[] object = null;
final Class[] columnsTypes = types;
final boolean[] canEdit = editable;
// We define the data model with the type of the columns and whether or not editable.
// Definimos el modelo de datos con el tipo de las columnas y si son o no editables.
tableModel = new DefaultTableModel(
new Object[][]{},
columns
) {
/**
* We override the method to define our type of columns.
* Sobreescribimos el método para definir nuestro tipo de columnas.
* @param columnIndex the column being queried (la columna que está consultando)
* @return the Object.class (la clase del objeto)
*/
@Override
public Class getColumnClass(int columnIndex) {
return columnsTypes[columnIndex];
}
/**
* We override the method to select the editable columns.
* Sobre escribimos el método para seleccionar las columnas editables.
* @param rowIndex the row being queried (la fila que está consultando)
* @param columnIndex the column being queried (la columna que está consultando)
* @return the Object.class (la clase del objeto)
*/
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
};
// We create the table.
// Creamos una nueva tabla.
jTable = new JTable();
// We assign our data model to the JTable.
// Le asignamos nuestro modelo de datos al JTable.
jTable.setModel(tableModel);
// We associate our table again to JScrollPane.
// Asociamos de nuevo nuestra tabla al JScrollPane.
jScrollPane.setViewportView(jTable);
for (int i = 0; i < jTable.getColumnModel().getColumnCount(); i++) {
jTable.getColumnModel().getColumn(i).setPreferredWidth(columnsWidth[i]);
}
// With this method we generate automatic sorting in columns.
// Con este método generamos ordenación automática en las columnas.
jTable.setAutoCreateRowSorter(true);
object = new Object[]{jTable, jScrollPane, tableModel};
return object;
}
/**
* 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);
}
}
/**
* Explanation of the method by which we read the JTable we pass as
* parameter, and where we copy its content in a excel spreadsheet passed
* as a parameter.
* Método con el que leemos cualquier JTable que pasamos como
* parámetro, y donde copiamos su contenido en una hoja excel que se pasa
* como parámetro.
* <h3>Example (Ejemplo)</h3>
* <pre>
* utilJTableToExcel(jTable2, new File("excelJTable.xls"), getTitle() + " (Código Xules)", "JTable");
* </pre>
*
* @param jTable <code>JTable</code>
* the JTable we are going to extract to excel
* El Jtable que vamos a extraer a excel.
* @param excelNewFile <code>String</code>
* excel File we are going to write.
* Fichero excel en el que vamos a escribir.
* @param title <code>String</code>
* title
* Título
* @param sheetName <code>String</code>
* Name of the sheet
* Nombre de la hoja
*/
public void utilJTableToExcel(JTable jTable, File excelNewFile, String title, String sheetName){
OutputStream excelNewOutputStream = null;
try {
excelNewOutputStream = new FileOutputStream(excelNewFile);
// High level representation of a workbook.
// Representación del más alto nivel de la hoja excel.
HSSFWorkbook hssfWorkbookNew = new HSSFWorkbook();
// We create the new sheet we are going to use.
// Creamos la hoja nueva que vamos a utilizar.
HSSFSheet hssfSheetNew = hssfWorkbookNew.createSheet(sheetName);
// An object that allows us to read a row of the excel sheet, and extract from it the cell contents.
// Objeto que nos permite leer un fila de la hoja excel, y de aquí extraer el contenido de las celdas.
HSSFRow hssfRowNew;
// Initialize the object to read the value of the cell
// Inicializo el objeto que leerá el valor de la celda
HSSFCell cellNew;
// Creating title row (creando una fila con el título)
hssfRowNew = hssfSheetNew.createRow(1);
cellNew = hssfRowNew.createCell(1);
cellNew.setCellType(HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue(title);
// We create the titles of the columns.
hssfRowNew = hssfSheetNew.createRow(4);
for (int column = 0; column < jTable.getColumnCount(); column++) {
cellNew = hssfRowNew.createCell(column);
cellNew.setCellType(HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue((String)jTable.getColumnName(column));
}
// Now we fill the excel spreatsheet.
// Ahora llenamos la hoja de cálculo excel.
for (int row = 0; row < jTable.getRowCount(); row++) {
hssfRowNew = hssfSheetNew.createRow(row + 5);
for (int column = 0; column < jTable.getColumnCount(); column++) {
cellNew = hssfRowNew.createCell(column);
if (jTable.getColumnClass(column).equals(java.lang.Boolean.class)){
cellNew.setCellValue((Boolean)jTable.getValueAt(row, column));
}else if (jTable.getColumnClass(column).equals(java.util.Date.class)){
cellNew.setCellValue((java.util.Date)jTable.getValueAt(row, column));
}else if (jTable.getColumnClass(column).equals(java.lang.Integer.class) ||
jTable.getColumnClass(column).equals(java.lang.Float.class) ||
jTable.getColumnClass(column).equals(java.lang.Double.class)){
cellNew.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cellNew.setCellValue((Double)jTable.getValueAt(row, column));
}else{
cellNew.setCellType(HSSFCell.CELL_TYPE_STRING);
cellNew.setCellValue((String)jTable.getValueAt(row, column));
}
}
}
hssfWorkbookNew.write(excelNewOutputStream);
excelNewOutputStream.close();
JOptionPane.showMessageDialog(this.jPanelQuery, "Your excel file has been generated!(¡Se ha generado tu hoja excel!",
"RESULTADO", JOptionPane.INFORMATION_MESSAGE);
} catch (FileNotFoundException fileNotFoundException) {
JOptionPane.showMessageDialog(this.jPanelQuery, "The file not exists (No se encontró el fichero): " + fileNotFoundException,
"ERROR", JOptionPane.ERROR_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(this.jPanelQuery, "Error in file procesing (Error al procesar el fichero): " + ex,
"ERROR", JOptionPane.ERROR_MESSAGE);
}
}
/**
* We get the database connection.
* Obtenemos la conexión a la base de datos.
* @return <code>Connection</code> database connection (conexión a la base de datos).
*/
public Connection getConnection() {
return connection;
}
/**
* We set the database connection.
* Definimos la conexíoin a la base de datos.
* @param connection <code>Connection</code> set database connection (definimos la conexión a la base de datos).
*/
public void setConnection(Connection connection) {
this.connection = connection;
}
/**
* 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() {
jPanelQuery = new javax.swing.JPanel();
jScrollPaneQuery = new javax.swing.JScrollPane();
jTableQuery = new javax.swing.JTable();
jButtonExcelExport = new javax.swing.JButton();
jButtonOut = new javax.swing.JButton();
jButtonImprimir = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("CARGAR CONSULTA PARA EXPORTAR");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jPanelQuery.setBorder(javax.swing.BorderFactory.createTitledBorder("Carga consulta para exportar"));
jTableQuery.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{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"
}
));
jScrollPaneQuery.setViewportView(jTableQuery);
javax.swing.GroupLayout jPanelQueryLayout = new javax.swing.GroupLayout(jPanelQuery);
jPanelQuery.setLayout(jPanelQueryLayout);
jPanelQueryLayout.setHorizontalGroup(
jPanelQueryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPaneQuery, javax.swing.GroupLayout.DEFAULT_SIZE, 488, Short.MAX_VALUE)
);
jPanelQueryLayout.setVerticalGroup(
jPanelQueryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelQueryLayout.createSequentialGroup()
.addComponent(jScrollPaneQuery)
.addContainerGap())
);
jButtonExcelExport.setText("EXPORTAR A EXCEL");
jButtonExcelExport.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonExcelExportActionPerformed(evt);
}
});
jButtonOut.setText("SALIR");
jButtonOut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOutActionPerformed(evt);
}
});
jButtonImprimir.setText("IMPRIMIR");
jButtonImprimir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonImprimirActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelQuery, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jButtonExcelExport)
.addGap(30, 30, 30)
.addComponent(jButtonImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonOut, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanelQuery, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonOut)
.addComponent(jButtonExcelExport)
.addComponent(jButtonImprimir))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* Button to export the table to excel.
* Botón para exportar the table to excel.
* @param evt button event (evento del botón).
*/
private void jButtonExcelExportActionPerformed(java.awt.event.ActionEvent evt) {
utilJTableToExcel(jTableQuery, new File("excelJTable.xls"), getTitle() + " (Código Xules)", "JTable");
}
/**
* Exit button.
* Botón de salida.
* @param evt button event (evento del botón).
*/
private void jButtonOutActionPerformed(java.awt.event.ActionEvent evt) {
try {
getConnection().close();
} catch (SQLException ex) {
Logger.getLogger(JFrameJTableDatabaseToExcelExampleMas.class.getName()).log(Level.SEVERE, null, ex);
}
dispose();
}
/**
* Exit JFrame.
* Salida de JFrame.
* @param evt button event (evento del botón).
*/
private void formWindowClosing(java.awt.event.WindowEvent evt) {
try {
// Connection close (cierre de la conexión).
getConnection().close();
} catch (SQLException ex) {
Logger.getLogger(JFrameJTableDatabaseToExcelExampleMas.class.getName()).log(Level.SEVERE, null, ex);
}
dispose();
}
private void jButtonImprimirActionPerformed(java.awt.event.ActionEvent evt) {
utilJTablePrint(jTableQuery, getTitle(), "Código Xules", true);
}
/**
* @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;
}
}
// Load the System look and feel (cargamos el "look and feel" del sistema.
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(JFrameJTableDatabaseToExcelExampleMas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JFrameJTableDatabaseToExcelExampleMas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JFrameJTableDatabaseToExcelExampleMas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JFrameJTableDatabaseToExcelExampleMas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/**
* Create and display the form.
* Creamos y mostramos el form.
*/
java.awt.EventQueue.invokeLater(new Runnable() {
/**
*
*/
public void run() {
String consulta =
"SELECT idlanguage, namelanguage, isactive, languageiso, countrycode, \n" +
" isbaselanguage, issystemlanguage\n" +
" FROM cb_language";
JFrameJTableDatabaseToExcelExampleMas jFrameJTableDatabaseToExcelExample =
new JFrameJTableDatabaseToExcelExampleMas(consulta,
new String[] {"IDIOMA", "NOMBRE", "ACTIVO", "ISO", "PAÍS", "BASE", "SISTEMA"},
new Class[] {java.lang.String.class, java.lang.String.class, java.lang.String.class,
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class},
new boolean[]{false, false, false, false, false, false, false},
new int[]{100, 100, 80, 80, 80, 60, 60}
);
jFrameJTableDatabaseToExcelExample =
new JFrameJTableDatabaseToExcelExampleMas(consulta,
new String[] {"IDIOMA", "NOMBRE", "ACTIVO", "ISO", "PAÍS"},
new Class[] {java.lang.String.class, java.lang.String.class, java.lang.String.class,
java.lang.String.class, java.lang.String.class},
new boolean[]{false, false, false, false, false},
new int[]{100, 100, 80, 80, 80}
);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButtonExcelExport;
private javax.swing.JButton jButtonImprimir;
private javax.swing.JButton jButtonOut;
private javax.swing.JPanel jPanelQuery;
private javax.swing.JScrollPane jScrollPaneQuery;
private javax.swing.JTable jTableQuery;
// End of variables declaration
}
Añadimos un nuevo botón a nuestro código y copiamos el método del ejemplo: http://www.lawebdelprogramador.com/codigo/Java/3412-Imprimir-JTable-directamente-en-Java.html
Así que lo único nuevo es el código de creación del botón y la llamada en el método:
}