Bom dia Galera do GUJ
Meu código está dando erro no Array, e já tentei resolver, procurei vídeos e artigos por toda internet e ainda não achei uma solução, sei que é uma coisa simples mas não conseguir resolver
segue os códigos abaixo
package VisionMenus;
import BDLicipa.bd_licipa;
import Models.*;
import Control.*;
import com.itextpdf.io.IOException;
import static com.itextpdf.kernel.pdf.PdfName.Font;
import com.itextpdf.layout.element.Paragraph;
import java.awt.Component;
import java.awt.Font;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.TableModel;
import static org.apache.poi.hssf.usermodel.HeaderFooter.file;
public class TelaRelGeral extends javax.swing.JFrame {
bd_licipa conecta = new bd_licipa();
public TelaRelGeral() {
initComponents();
conecta.conexao();
preenchertabela("select * from indice_licipa order by id_indice");
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel3 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
JTGeralIndice = new javax.swing.JTable();
JBExportar = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Tela Relatório Geral - LICIPA");
getContentPane().setLayout(null);
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("Relatório Geral do Índice");
getContentPane().add(jLabel3);
jLabel3.setBounds(0, 0, 710, 60);
jScrollPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 51, 255), 2));
JTGeralIndice.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
JTGeralIndice.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
JTGeralIndice.setEnabled(false);
jScrollPane1.setViewportView(JTGeralIndice);
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(12, 60, 690, 410);
JBExportar.setBackground(new java.awt.Color(0, 0, 102));
JBExportar.setForeground(new java.awt.Color(255, 255, 255));
JBExportar.setText("Exportar Tabela Para Arquivo ");
JBExportar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JBExportarActionPerformed(evt);
}
});
getContentPane().add(JBExportar);
JBExportar.setBounds(240, 483, 230, 30);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagem/background blue grande.jpg"))); // NOI18N
getContentPane().add(jLabel1);
jLabel1.setBounds(0, -40, 710, 570);
setSize(new java.awt.Dimension(726, 567));
setLocationRelativeTo(null);
}// </editor-fold>
private void JBExportarActionPerformed(java.awt.event.ActionEvent evt) {
exportarExcel(JTGeralIndice);
//toExcel(JTGeralIndice, new File("arq.teste.xls"));
}
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;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TelaRelGeral.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaRelGeral.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaRelGeral.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaRelGeral.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TelaRelGeral().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton JBExportar;
private javax.swing.JTable JTGeralIndice;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
private void preenchertabela(String SQL) {
ArrayList dados = new ArrayList();
String[] Colunas = new String[]{"N_Proces", "Modal", "Nº Modal", "Emis", "Abert", "Dia", "Mes", "Ano", "Objet", "Venc", "Cpf/Cnpj", "N_Cont", "DT_Cont", "Val_Cont", "Vigen", "Orgão", "Unid", "Gest"};
conecta.executaSQL(SQL);
try {
conecta.rs.first();
do {
dados.add(new Object[]{conecta.rs.getString("nprocesso_indice"), conecta.rs.getString("modalidade_indice"), conecta.rs.getString("emissao_indice"), conecta.rs.getString("abertura_indice"), conecta.rs.getString("fk_inddia"), conecta.rs.getString("fk_indmes"), conecta.rs.getString("fk_indano"), conecta.rs.getString("objeto_indice"), conecta.rs.getString("vencedor_indice"), conecta.rs.getString("cpfcnpj_indice"), conecta.rs.getString("ncontrato_indice"), conecta.rs.getString("dtcontrato_indice"), conecta.rs.getString("valorcontrato_indice"), conecta.rs.getString("vigencia_indice"), conecta.rs.getString("fk_indori"), conecta.rs.getString("fk_induni"), conecta.rs.getString("gestor_indice")});
} while (conecta.rs.next());
} catch (SQLException ex) {
Logger.getLogger(TelaRelGeral.class.getName()).log(Level.SEVERE, null, ex);
}
ModTab mt = new ModTab(dados, Colunas);
JTGeralIndice.setModel(mt);
JTGeralIndice.getColumnModel().getColumn(0).setPreferredWidth(70);
JTGeralIndice.getColumnModel().getColumn(0).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(1).setPreferredWidth(70);
JTGeralIndice.getColumnModel().getColumn(1).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(2).setPreferredWidth(70);
JTGeralIndice.getColumnModel().getColumn(2).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(3).setPreferredWidth(70);
JTGeralIndice.getColumnModel().getColumn(3).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(4).setPreferredWidth(70);
JTGeralIndice.getColumnModel().getColumn(4).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(5).setPreferredWidth(70);
JTGeralIndice.getColumnModel().getColumn(5).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(6).setPreferredWidth(70);
JTGeralIndice.getColumnModel().getColumn(6).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(7).setPreferredWidth(70);
JTGeralIndice.getColumnModel().getColumn(7).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(8).setPreferredWidth(400);
JTGeralIndice.getColumnModel().getColumn(8).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(9).setPreferredWidth(70);
JTGeralIndice.getColumnModel().getColumn(9).setResizable(false);
/*JTGeralIndice.getColumnModel().getColumn(10).setPreferredWidth(40);
JTGeralIndice.getColumnModel().getColumn(10).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(11).setPreferredWidth(40);
JTGeralIndice.getColumnModel().getColumn(11).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(12).setPreferredWidth(40);
JTGeralIndice.getColumnModel().getColumn(12).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(13).setPreferredWidth(40);
JTGeralIndice.getColumnModel().getColumn(13).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(14).setPreferredWidth(40);
JTGeralIndice.getColumnModel().getColumn(14).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(15).setPreferredWidth(40);
JTGeralIndice.getColumnModel().getColumn(15).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(16).setPreferredWidth(40);
JTGeralIndice.getColumnModel().getColumn(16).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(17).setPreferredWidth(40);
JTGeralIndice.getColumnModel().getColumn(17).setResizable(false);
JTGeralIndice.getColumnModel().getColumn(18).setPreferredWidth(40);
JTGeralIndice.getColumnModel().getColumn(18).setResizable(false);*/
JTGeralIndice.getTableHeader().setReorderingAllowed(false);
JTGeralIndice.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JTGeralIndice.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
/**
*
* @param table
*/
public void exportarExcel(JTable table) { // salva a um jtable em xls
{
JFileChooser fc = new JFileChooser();
int option = fc.showSaveDialog(table); // da erro aqui
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if (len > 4) {
ext = filename.substring(len - 4, len);
}
if (ext.equals(".xlsx")) {
file = path + "\\" + filename;
} else {
file = path + "\\" + filename + ".xlsx";
}
try {
toExcel(table, new File(file));
} catch (IOException ex) {
}
}
}
}
public void toExcel(JTable table, File file) throws IOException { // auxilia o metodo a cima
try {
TableModel model = table.getModel();
FileWriter excel;
excel = new FileWriter(file);
for (int i = 0; i < model.getColumnCount(); i++) {
excel.write(model.getColumnName(i) + "\t");
}
excel.write("\n");
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
excel.write(model.getValueAt(i, j).toString() + "\t");
}
excel.write("\n");
}
excel.close();
JOptionPane.showMessageDialog(null, "Salvo em: " + file);
//System.out.println("Salvo em: " + file);
} catch (java.io.IOException ex) {
JOptionPane.showMessageDialog(null, "Erro no processo\n Erro:" + ex);
}
}
}
> Bloco de citação
package Models;
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
public class ModTab extends AbstractTableModel{
private ArrayList linhas = null;
private String[] colunas = null;
public ModTab(ArrayList lin, String[] col) {
setLinhas(lin);
setColunas(col);
}
public ArrayList getLinhas(){
return linhas;
}
public void setLinhas(ArrayList linhs){
linhas = linhs;
}
public String[] getColunas(){
return colunas;
}
public void setColunas(String[] coluns){
colunas = coluns;
}
public int getColumnCount(){
return colunas.length;
}
public int getRowCount(){
return linhas.size();
}
public String getColumnName(int numCol){
return colunas[numCol];
}
public Object getValueAt(int numLin, int numCol){
Object[] linha = (Object[])getLinhas().get(numLin);
return linha[numCol];
}
}
Erro:
run:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 17
at Models.ModTab.getColumnName(ModTab.java:42)
at VisionMenus.TelaRelGeral.toExcel(TelaRelGeral.java:261)
at VisionMenus.TelaRelGeral.exportarExcel(TelaRelGeral.java:245)
at VisionMenus.TelaRelGeral.JBExportarActionPerformed(TelaRelGeral.java:99)
at VisionMenus.TelaRelGeral.access$000(TelaRelGeral.java:25)
at VisionMenus.TelaRelGeral$1.actionPerformed(TelaRelGeral.java:83)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6539)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6304)
at java.awt.Container.processEvent(Container.java:2239)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2297)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
at java.awt.Container.dispatchEventImpl(Container.java:2283)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
at java.awt.EventQueue$4.run(EventQueue.java:733)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)