Fiz uma aplicação simples que efetua o processamento do texto (ascii) extraído de um arquivo PDF e gera como resultado um outro arquivo texto o qual é exibido num jTextArea. O programa funciona normalmente, no entanto, a barra de progresso não funciona. Utilizei a classe SwingWorker mas, por não saber utilizá-la corretamente, algo saiu errado, só não sei o que.
A classe que faz o processamento é a LePDF.java, que está no package "Engine". A GUI (JFrame1.java) está no package "pdfsinapi" e é nela que utilizo a classe LePDF para obter o resultado e imprimí-lo na tela. O projeto foi feito no NetBeans 6.9.
Segue abaixo, o código principal da GUI, o JFrame1.java:
/*
* JFrame1.java
*
* Criado emn 05/08/2010, 21:39:02
*/
package pdfsinapi;
import Engine.ClipBoard;
import Engine.Dados;
import Engine.LePDF;
import java.awt.Desktop;
import java.beans.PropertyChangeEvent;
import java.io.IOException;
import javax.swing.JOptionPane;
import java.awt.Dimension; // Acrescentei esta linha
import java.awt.Toolkit; // Acrescentei esta linha
import java.beans.PropertyChangeListener; // Acrescentei esta linha
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
/**
*
* @author Marcelo Magalhães Macedo
*/
public class JFrame1 extends javax.swing.JFrame implements PropertyChangeListener {
{ /** Coloca o Look & Feel default do sistema */
try {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
ImprimeErro(e.toString());
}
}
/** Cria novo form JFrame1 */
public JFrame1() {
initComponents();
/* -------- Acrescentei a linha abaixo para mudar o ícone da aplicação (do JAR)
* O arquivo .png deve estar no mesmo diretório do arquivo JAR. */
setIconImage(new ImageIcon("PDFSinapi.png").getImage());
jTextArea1.setCaretPosition(0); // Coloca o cursor na primeira linha do jTextArea1
jTextArea2.setCaretPosition(0); // Coloca o cursor na primeira linha do jTextArea2
Saida = "";
ArqAtual = null;
SaidaAtual = null;
}
/** 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() {
buttonGroup1 = new javax.swing.ButtonGroup();
PopupMenuEnt = new javax.swing.JPopupMenu();
PopupMenuEnt_itemCopTudo = new javax.swing.JMenuItem();
PopupMenuEnt_itemCopSel = new javax.swing.JMenuItem();
PopupMenuSaida = new javax.swing.JPopupMenu();
PopupMenuSaida_itemCopTudo = new javax.swing.JMenuItem();
PopupMenuSaida_itemCopSel = new javax.swing.JMenuItem();
buttonGroup_LAF = new javax.swing.ButtonGroup();
StatusPanel = new javax.swing.JPanel();
jLabelStatusBar = new javax.swing.JLabel();
jProgressBar1 = new javax.swing.JProgressBar();
jPanel1 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton1 = new javax.swing.JRadioButton();
jTextField_Delimitador = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jButton3 = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jPanel3 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
jMenuItem4 = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
jRadioButtonMenuItem1 = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItem2 = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItem4 = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItem3 = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItem5 = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItem6 = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItem7 = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItem8 = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItem9 = new javax.swing.JRadioButtonMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenuItem6 = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JPopupMenu.Separator();
jMenuItem5 = new javax.swing.JMenuItem();
PopupMenuEnt_itemCopTudo.setMnemonic('C');
PopupMenuEnt_itemCopTudo.setText("Copiar Tudo");
PopupMenuEnt_itemCopTudo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PopupMenuEnt_itemCopTudoActionPerformed(evt);
}
});
PopupMenuEnt.add(PopupMenuEnt_itemCopTudo);
PopupMenuEnt_itemCopSel.setMnemonic('S');
PopupMenuEnt_itemCopSel.setText("Copiar Seleção");
PopupMenuEnt_itemCopSel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PopupMenuEnt_itemCopSelActionPerformed(evt);
}
});
PopupMenuEnt.add(PopupMenuEnt_itemCopSel);
PopupMenuEnt.getAccessibleContext().setAccessibleParent(jTextArea2);
PopupMenuSaida_itemCopTudo.setMnemonic('C');
PopupMenuSaida_itemCopTudo.setText("Copiar Tudo");
PopupMenuSaida_itemCopTudo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PopupMenuSaida_itemCopTudoActionPerformed(evt);
}
});
PopupMenuSaida.add(PopupMenuSaida_itemCopTudo);
PopupMenuSaida_itemCopSel.setMnemonic('S');
PopupMenuSaida_itemCopSel.setText("Copiar Seleção");
PopupMenuSaida_itemCopSel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PopupMenuSaida_itemCopSelActionPerformed(evt);
}
});
PopupMenuSaida.add(PopupMenuSaida_itemCopSel);
PopupMenuSaida.getAccessibleContext().setAccessibleParent(jTextArea1);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("PDFSinapi V 1.0");
setIconImages(null);
setMinimumSize(new java.awt.Dimension(800, 600));
StatusPanel.setPreferredSize(new java.awt.Dimension(800, 29));
jProgressBar1.setStringPainted(true);
javax.swing.GroupLayout StatusPanelLayout = new javax.swing.GroupLayout(StatusPanel);
StatusPanel.setLayout(StatusPanelLayout);
StatusPanelLayout.setHorizontalGroup(
StatusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(StatusPanelLayout.createSequentialGroup()
.addComponent(jLabelStatusBar)
.addContainerGap(800, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, StatusPanelLayout.createSequentialGroup()
.addContainerGap(631, Short.MAX_VALUE)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE))
);
StatusPanelLayout.setVerticalGroup(
StatusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(StatusPanelLayout.createSequentialGroup()
.addGroup(StatusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelStatusBar)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros"));
jLabel3.setLabelFor(jTextField1);
jLabel3.setText("Mês Base:");
jTextField1.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextField2.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jLabel4.setLabelFor(jTextField2);
jLabel4.setText("Encargos Sociais (%):");
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pdfsinapi/open.png"))); // NOI18N
jButton1.setMnemonic('A');
jButton1.setText("Abrir arquivo PDF Sinapi (F5)");
jButton1.setPreferredSize(new java.awt.Dimension(167, 33));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pdfsinapi/copy.png"))); // NOI18N
jButton2.setMnemonic('C');
jButton2.setText("Copiar saída p/ Clipboard (F8)");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jPanel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());
buttonGroup1.add(jRadioButton2);
jRadioButton2.setMnemonic('O');
jRadioButton2.setText("Outro:");
jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton2ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton1);
jRadioButton1.setMnemonic('P');
jRadioButton1.setSelected(true);
jRadioButton1.setText("Padrão (Tabulação)");
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1ActionPerformed(evt);
}
});
jTextField_Delimitador.setFont(new java.awt.Font("Tahoma", 1, 11));
jTextField_Delimitador.setHorizontalAlignment(javax.swing.JTextField.LEFT);
jTextField_Delimitador.setText("|");
jTextField_Delimitador.setEnabled(false);
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11));
jLabel5.setText(" Delimitador de texto de saída:");
jLabel5.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jRadioButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField_Delimitador, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE))
.addComponent(jRadioButton1))
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(7, 7, 7)
.addComponent(jRadioButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jRadioButton2)
.addComponent(jTextField_Delimitador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(10, Short.MAX_VALUE))
);
jLabel6.setLabelFor(jComboBox1);
jLabel6.setText("Tamanho da fonte:");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "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" }));
jComboBox1.setSelectedIndex(10);
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pdfsinapi/save.png"))); // NOI18N
jButton3.setMnemonic('T');
jButton3.setText("Gravar saída em TXT (F9)");
jButton3.setActionCommand("Gerar arq. TXT da saída");
jButton3.setEnabled(false);
jButton3.setPreferredSize(new java.awt.Dimension(167, 33));
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 74, Short.MAX_VALUE)
.addComponent(jTextField2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 74, Short.MAX_VALUE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(17, 17, 17)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
.addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(8, 8, 8)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(26, Short.MAX_VALUE))
);
jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel1.setLabelFor(jTextArea1);
jLabel1.setText("Saída Gerada:");
jTextArea1.setBackground(java.awt.SystemColor.menu);
jTextArea1.setColumns(20);
jTextArea1.setEditable(false);
jTextArea1.setFont(new java.awt.Font("Monospaced", 0, 11));
jTextArea1.setForeground(new java.awt.Color(0, 51, 204));
jTextArea1.setRows(5);
jTextArea1.setBorder(null);
jTextArea1.setComponentPopupMenu(PopupMenuSaida);
jScrollPane1.setViewportView(jTextArea1);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addContainerGap(718, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 796, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE))
);
jLabel2.setLabelFor(jTextArea2);
jLabel2.setText("Texto extraído do PDF:");
jScrollPane2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jTextArea2.setColumns(20);
jTextArea2.setEditable(false);
jTextArea2.setFont(new java.awt.Font("Monospaced", 0, 11));
jTextArea2.setRows(5);
jTextArea2.setComponentPopupMenu(PopupMenuEnt);
jTextArea2.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jScrollPane2.setViewportView(jTextArea2);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2)
.addContainerGap(463, Short.MAX_VALUE))
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 575, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE))
);
jMenu1.setMnemonic('A');
jMenu1.setText("Arquivo");
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
jMenuItem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pdfsinapi/open.png"))); // NOI18N
jMenuItem1.setMnemonic('A');
jMenuItem1.setText("Abrir arquivo PDF do Sinapi");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F8, 0));
jMenuItem2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pdfsinapi/copy.png"))); // NOI18N
jMenuItem2.setMnemonic('C');
jMenuItem2.setText("Copiar saída para o Clipboard");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem2);
jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F9, 0));
jMenuItem3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pdfsinapi/save.png"))); // NOI18N
jMenuItem3.setMnemonic('T');
jMenuItem3.setText("Gravar saída em TXT");
jMenuItem3.setEnabled(false);
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem3);
jMenu1.add(jSeparator1);
jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem4.setMnemonic('S');
jMenuItem4.setText("Sair");
jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem4ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem4);
jMenuBar1.add(jMenu1);
jMenu3.setMnemonic('P');
jMenu3.setText("Aparência");
buttonGroup_LAF.add(jRadioButtonMenuItem1);
jRadioButtonMenuItem1.setMnemonic('S');
jRadioButtonMenuItem1.setSelected(true);
jRadioButtonMenuItem1.setText("Sistema");
jRadioButtonMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItem1ActionPerformed(evt);
}
});
jMenu3.add(jRadioButtonMenuItem1);
buttonGroup_LAF.add(jRadioButtonMenuItem2);
jRadioButtonMenuItem2.setMnemonic('X');
jRadioButtonMenuItem2.setText("Metal");
jRadioButtonMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItem2ActionPerformed(evt);
}
});
jMenu3.add(jRadioButtonMenuItem2);
buttonGroup_LAF.add(jRadioButtonMenuItem4);
jRadioButtonMenuItem4.setMnemonic('P');
jRadioButtonMenuItem4.setText("Plastic");
jRadioButtonMenuItem4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItem4ActionPerformed(evt);
}
});
jMenu3.add(jRadioButtonMenuItem4);
buttonGroup_LAF.add(jRadioButtonMenuItem3);
jRadioButtonMenuItem3.setMnemonic('D');
jRadioButtonMenuItem3.setText("Plastic 3D");
jRadioButtonMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItem3ActionPerformed(evt);
}
});
jMenu3.add(jRadioButtonMenuItem3);
buttonGroup_LAF.add(jRadioButtonMenuItem5);
jRadioButtonMenuItem5.setMnemonic('M');
jRadioButtonMenuItem5.setText("Plastic XP");
jRadioButtonMenuItem5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItem5ActionPerformed(evt);
}
});
jMenu3.add(jRadioButtonMenuItem5);
buttonGroup_LAF.add(jRadioButtonMenuItem6);
jRadioButtonMenuItem6.setMnemonic('N');
jRadioButtonMenuItem6.setText("Nimbus");
jRadioButtonMenuItem6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItem6ActionPerformed(evt);
}
});
jMenu3.add(jRadioButtonMenuItem6);
buttonGroup_LAF.add(jRadioButtonMenuItem7);
jRadioButtonMenuItem7.setMnemonic('F');
jRadioButtonMenuItem7.setText("Motif");
jRadioButtonMenuItem7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItem7ActionPerformed(evt);
}
});
jMenu3.add(jRadioButtonMenuItem7);
buttonGroup_LAF.add(jRadioButtonMenuItem8);
jRadioButtonMenuItem8.setMnemonic('W');
jRadioButtonMenuItem8.setText("Windows");
jRadioButtonMenuItem8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItem8ActionPerformed(evt);
}
});
jMenu3.add(jRadioButtonMenuItem8);
buttonGroup_LAF.add(jRadioButtonMenuItem9);
jRadioButtonMenuItem9.setMnemonic('I');
jRadioButtonMenuItem9.setText("Windows Classic");
jRadioButtonMenuItem9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItem9ActionPerformed(evt);
}
});
jMenu3.add(jRadioButtonMenuItem9);
jMenuBar1.add(jMenu3);
jMenu2.setMnemonic('S');
jMenu2.setText("Sobre");
jMenuItem6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pdfsinapi/Help.png"))); // NOI18N
jMenuItem6.setMnemonic('I');
jMenuItem6.setText("Instruções");
jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem6ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem6);
jMenu2.add(jSeparator2);
jMenuItem5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pdfsinapi/Sobre.png"))); // NOI18N
jMenuItem5.setMnemonic('S');
jMenuItem5.setText("Sobre");
jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem5ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem5);
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(StatusPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(StatusPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField_Delimitador.setEnabled(false);
}
private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField_Delimitador.setEnabled(true);
}
/* -------- Menu "Sobre"
*/
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {
dialogoSobre = new DlgSobre();
dialogoSobre.setLocationRelativeTo(this); // Centraliza o diálogo "Sobre"
dialogoSobre.setVisible(true);
}
/* -------- Popup Copiar Tudo - Entrada
*/
private void PopupMenuEnt_itemCopTudoActionPerformed(java.awt.event.ActionEvent evt) {
new ClipBoard().setString(jTextArea2.getText());
}
/* -------- Altera o tamanho da fonte dos jTextArea
*/
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea2.setFont(new java.awt.Font("Monospaced", 0,
Integer.parseInt(jComboBox1.getSelectedItem().toString())));
jTextArea1.setFont(new java.awt.Font("Monospaced", 0,
Integer.parseInt(jComboBox1.getSelectedItem().toString())));
}
/* -------- Botão Gravar saída em TXT
*/
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
/* -------- Menu Sair
*/
private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit( 0 );
}
/* -------- Popup Copiar Tudo - Saída
*/
private void PopupMenuSaida_itemCopTudoActionPerformed(java.awt.event.ActionEvent evt) {
new ClipBoard().setString(jTextArea1.getText());
}
/* -------- Menu "Instruções"
*
* Abre o arquivo no leitor default do sistema.
* O arquivo PDF deve estar no Diretório do JAR. Para o caso de testes
* o mesmo arquivo pode estra na pasta "..\NetBeansProjects\PDFSinapi\"
* Obs: Não deu certo o nome com "ç" e "õ".
*/
private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Desktop.getDesktop().open(new File("Instrucoes.pdf"));
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane,
"Não é possível abrir o arquivo \"Instrucoes.pdf\".",
"Erro !", JOptionPane.ERROR_MESSAGE);
ImprimeErro(e.toString());
}
/* -------- Código antigo: abria o Instrucoes.txt num diálogo:
try {
dialogoInstrucoes = new DlgInst();
} catch (IOException ex) {
JOptionPane.showMessageDialog(rootPane, "Impossível abrir o arquivo \"Instrucoes.txt\"");
Logger.getLogger(JFrame1.class.getName()).log(Level.SEVERE, null, ex);
}
dialogoInstrucoes.setLocationRelativeTo(this); // Centraliza o diálogo "Instr"
dialogoInstrucoes.setVisible(true);
*/
}
/* LookAndFeel do sistema
*/
private void jRadioButtonMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
SetLaf(javax.swing.UIManager.getSystemLookAndFeelClassName());
}
/* LookAndFeel Metal
*/
private void jRadioButtonMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
SetLaf("javax.swing.plaf.metal.MetalLookAndFeel");
}
/* LookAndFeel Plastic
*/
private void jRadioButtonMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {
SetLaf("com.jgoodies.looks.plastic.PlasticLookAndFeel");
}
/* LookAndFeel Plastic 3D
*/
private void jRadioButtonMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
SetLaf("com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
}
/* LookAndFeel PlasticXP
*/
private void jRadioButtonMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {
SetLaf("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
}
/* LookAndFeel Nimbus
*/
private void jRadioButtonMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {
SetLaf("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
/* LookAndFeel Motif
*/
private void jRadioButtonMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {
SetLaf("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}
/* LookAndFeel Windows
*/
private void jRadioButtonMenuItem8ActionPerformed(java.awt.event.ActionEvent evt) {
SetLaf("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
/* LookAndFeel Windows Classic
*/
private void jRadioButtonMenuItem9ActionPerformed(java.awt.event.ActionEvent evt) {
SetLaf("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
}
/* -------- Menu Abrir arquivo PDF do Sinapi:
*/
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
/* --------------------------- FileChooser -------------------------- */
String Arquivo = "";
File arq = null;
JFileChooser fc = new JFileChooser(ArqAtual);
filtro f1 = new filtro(".pdf");
fc.addChoosableFileFilter(f1);
fc.setFileFilter(f1); // Define o filtro default
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setAcceptAllFileFilterUsed(false); // Desabilita a opção ALLFILES
int res = fc.showOpenDialog(this);
if (res == JFileChooser.APPROVE_OPTION) {
arq = fc.getSelectedFile().getAbsoluteFile();
Arquivo = arq.toString();
if (getExtensao(arq) == null) { // Se não for digitada a extensão..
Arquivo += fc.getFileFilter().getDescription();
}
}
/* ----------------------------------------------------------------- */
if (!Arquivo.equals("")) {
try {
String dl = jTextField_Delimitador.getText();
if (jRadioButton1.isSelected()) {
lePdf1 = new LePDF(Arquivo); // Opção com delimitador default
} else {
lePdf1 = new LePDF(Arquivo, dl);
}
lePdf1.addPropertyChangeListener(this);
lePdf1.execute();
Dados dados1 = lePdf1.get();
// jProgressBar1.setIndeterminate(true);
// lePdf1.processa();
// jProgressBar1.setIndeterminate(false);
if (dados1.Leu()) {
JOptionPane.showMessageDialog(rootPane, " Leu OKmmm: ");
jTextArea2.setText(dados1.GetTE());
jTextArea2.setCaretPosition(0);
jLabelStatusBar.setText(Arquivo);
jLabelStatusBar.setToolTipText(Arquivo);
jTextArea1.setText(dados1.GetInPro());
jTextArea1.setCaretPosition(0);
jTextField1.setText(dados1.GetData());
jTextField2.setText(dados1.GetEnSo());
jLabel1.setText("Saída Gerada:" + " ( " + dados1.GetQti() +
" insumos obtidos )");
Saida = dados1.GetInPro();
ArqAtual = arq;
jButton3.setEnabled(true);
jMenuItem3.setEnabled(true);
jButton2.requestFocus(); // Muda o foco para o jButton2
} else {
JOptionPane.showMessageDialog(rootPane,
"Não é possível abrir o arquivo PDF selecionado.",
"Erro !", JOptionPane.ERROR_MESSAGE);
jLabel1.setText("Saída Gerada:");
jLabelStatusBar.setText("");
jLabelStatusBar.setToolTipText("");
jTextArea1.setText("");
jTextArea2.setText("");
jTextField1.setText("");
jTextField2.setText("");
Saida = "";
ArqAtual = null;
}
} catch(Exception e) {
JOptionPane.showMessageDialog(rootPane,
"Ocorreu um erro!",
"Erro !", JOptionPane.ERROR_MESSAGE);
ImprimeErro(e.toString());
}
}
}
/* -------- Menu Gravar saída em TXT:
*/
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
if (!jTextArea1.getText().equals("")) {
String Arquivo = "";
File arq = null;
JFileChooser fc = new JFileChooser(SaidaAtual);
fc.setDialogTitle("Salvar");
filtro f1 = new filtro(".txt");
filtro f2 = new filtro(".csv");
fc.addChoosableFileFilter(f1);
fc.addChoosableFileFilter(f2);
fc.setFileFilter(f1); // Define o filtro default
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setAcceptAllFileFilterUsed(false); // Desabilita a opção ALLFILES
int res = fc.showSaveDialog(this);
if (res == JFileChooser.APPROVE_OPTION) {
arq = fc.getSelectedFile().getAbsoluteFile();
Arquivo = arq.toString();
if (getExtensao(arq) == null) { // Se não for digitada a extensão..
Arquivo += fc.getFileFilter().getDescription();
}
SaidaAtual = new File(Arquivo);
}
/* ---- Outra forma de criar filtros (não muito boa):
FileNameExtensionFilter filtro1 = new FileNameExtensionFilter("Documentos de texto (*.txt)", "txt");
FileNameExtensionFilter filtro2 = new FileNameExtensionFilter("Arquivo (*.csv)", "csv");
fc.addChoosableFileFilter(filtro2);
fc.addChoosableFileFilter(filtro1);
*/
if (!Arquivo.equals("")) {
try { // Grava, num arquivo texto, o conteúdo da variável "Saida"
OutputStream is = new FileOutputStream(Arquivo);
OutputStreamWriter osw = new OutputStreamWriter(is);
BufferedWriter bw = new BufferedWriter(osw);
try {
bw.write(this.Saida);
bw.close();
} catch (IOException e) {
ImprimeErro(e.toString());
}
} catch (FileNotFoundException e) {
ImprimeErro(e.toString());
}
}
}
}
/* -------- Classe auxiliar para obter a extensão de um arquivo
* obtém a extensão e o ponto.
*/
private static String getExtensao(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (f.isDirectory())
ext = null;
else if (i > 0 && i < s.length() - 1) {
ext = s.substring(i).toLowerCase();
}
return ext;
}
public void propertyChange(PropertyChangeEvent evt) {
if ("progress" == evt.getPropertyName()) {
int progress = (Integer)evt.getNewValue();
jProgressBar1.setIndeterminate(false);
jProgressBar1.getUI().update(jProgressBar1.getGraphics(), jProgressBar1);
jProgressBar1.repaint();
//jProgressBar1.setValue(lePdf1.getProgress());
jProgressBar1.setValue(progress);
//jProgressBar1.setValue(((Integer)evt.getNewValue()));
jTextArea1.append(String.format("Completado %d%% da tarefa.\n", lePdf1.getProgress()));
/* statusbar.text = "processando linha 1"; //-> implementar depois */
}
}
/* -------- Classe auxiliar para gerar filtro para o JFileChooser
* Para cada filtro, deve-se criar um objeto deste
* e usar mais um fc.addChoosableFileFilter(new filtroN());
*/
class filtro extends javax.swing.filechooser.FileFilter {
private final String ext;
filtro(String extensao) {
this.ext = extensao;
}
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
String filename = file.getName();
return filename.endsWith(ext);
}
public String getDescription() {
return ext;
}
}
/* -------- Botão Abrir arquivo PDF do Sinapi
*/
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
/* -------- Menu Copiar saída para o Clipboard:
*/
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
if (!jLabelStatusBar.getText().equals("")) {
ClipBoard clip = new ClipBoard();
clip.setString(jTextArea1.getText());
}
}
/* -------- Botão Copiar saída para o Clipboard:
*/
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
/* -------- Imprime mensagens de erro num diálogo à parte
*/
private void ImprimeErro(String Erro) {
dialogoInstrucoes = new DlgInst(Erro);
dialogoInstrucoes.setLocationRelativeTo(this); // Centraliza o diálogo "Instr"
dialogoInstrucoes.setVisible(true);
}
/* -------- Popup Copiar Seleção - Entrada
*/
private void PopupMenuEnt_itemCopSelActionPerformed(java.awt.event.ActionEvent evt) {
new ClipBoard().setString(jTextArea2.getSelectedText());
}
/* -------- Popup Copiar Seleção - Saída
*/
private void PopupMenuSaida_itemCopSelActionPerformed(java.awt.event.ActionEvent evt) {
new ClipBoard().setString(jTextArea1.getSelectedText());
}
/* -------- Muda o LookAndFeel, conforme seleção
*/
private void SetLaf(String laf) {
try {
javax.swing.UIManager.setLookAndFeel(laf);
SwingUtilities.updateComponentTreeUI(this);
} catch(Exception e) {
JOptionPane.showMessageDialog(rootPane,
"Não é possível mudar para essa aparência.",
"Erro !", JOptionPane.ERROR_MESSAGE);
ImprimeErro(e.toString());
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() { /* Alterei as linhas abaixo, para centralizar a janela: */
// new JFrame1().setVisible(true); -> linha original criada pelo NetBeans
JFrame1 Janela = new JFrame1();
// ---- Obtem o tamanho do screen:
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
// ---- Determina a nova localização da janela:
int w = Janela.getSize().width;
int h = Janela.getSize().height;
int x = (dim.width - w) / 2;
int y = (dim.height - h) / 2;
// ---- Move a janela:
Janela.setLocation(x, y);
Janela.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPopupMenu PopupMenuEnt;
private javax.swing.JMenuItem PopupMenuEnt_itemCopSel;
private javax.swing.JMenuItem PopupMenuEnt_itemCopTudo;
private javax.swing.JPopupMenu PopupMenuSaida;
private javax.swing.JMenuItem PopupMenuSaida_itemCopSel;
private javax.swing.JMenuItem PopupMenuSaida_itemCopTudo;
private javax.swing.JPanel StatusPanel;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup_LAF;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabelStatusBar;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JMenuItem jMenuItem6;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem1;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem2;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem3;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem4;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem5;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem6;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem7;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem8;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JPopupMenu.Separator jSeparator1;
private javax.swing.JPopupMenu.Separator jSeparator2;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextArea jTextArea2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField_Delimitador;
// End of variables declaration
private DlgSobre dialogoSobre; // Acrescentei esta linha
private DlgInst dialogoInstrucoes; // Acrescentei esta linha
//private DlgProgresso dlgProg; // Acrescentei esta linha
private String Saida; // Armazena a String de saída
private File ArqAtual; // Armazena o Path do arquivo PDF aberto
private File SaidaAtual; // Armazena o Path do último arquivo Saida
private LePDF lePdf1;
}
Segue abaixo, o código principal de processamento do arquivo texto, o LePDF.java:
package Engine;
/**
* ----------------------------------------------------------- LePDF.java
*
* Lê um arquivo PDF e retorna a saída formatada com os dados necessários
* ----------------------------------------------------------------------
* Recebe uma String, contendo todo o arquivo texto extraído do arquivo
* PDF e retorna outra String, contendo o conteúdo processado, já pronto
* para ser enviado para o clipboard ou para criação do arquivo csv.
* ----------------------------------------------------------------------
* @author Marcelo Magalhães Macedo
*/
//import Engine.Dados;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.ibm.icu.util.StringTokenizer;
import javax.swing.SwingWorker;
public class LePDF extends SwingWorker<Dados, Void>
{
private PdfParser pp;
private Dados dados1 ;
private String Ar; // Arquivo a ser processado
private String dl; // Delimitador
private String Delim; // Delimitador (separador dos campos dos insumos)
private int i; // Contador de linhas do arquivo
/* -------- Construtor
* Recebe como argumento o caminho do arquivo PDF
* e o delimitador a ser utilizado.
*/
public LePDF(String Ar, String dl) {
this.Ar = Ar;
this.dl = dl;
dados1 = new Dados();
dados1.SetTE("");
dados1.SetData("");
dados1.SetEnSo("");
dados1.SetQti("");
dados1.SetLeu(false);
}
/* -------- Construtor Sobrecarregado
* Recebe como argumento o caminho do arquivo PDF.
* Usa como default o delimitador padrão: "\t" = tabulação
*/
public LePDF(String Ar) {
this(Ar, "\t"); // Chama o construtor anterior utilizando Delimitador "\t"
}
/* -------- Faz o processamento do arquivo
*/
public void processa() {
pp = new PdfParser();
pp.setEnderecoRecurso(this.Ar);
dados1.SetTE(pp.getConteudo());
Delim = this.dl;
dados1.SetInPro(stx());
System.out.println("entrei no processa");/////////////////////////////////////////////
if (dados1.GetTE().startsWith("ERRO:") || dados1.GetTE().equals("")) {
dados1.SetLeu(false);
} else {
dados1.SetLeu(true);
}
}
/* -------- Formata a String para saída separada pelo delimitador "Delim"
*/
private String stx() {
List<Insumo> ArIn = new ArrayList<Insumo>(); // Array de insumos
StringReader is = new StringReader(dados1.GetTE());
/* Se for trabalhar com arquivo texto, basta mudar a linha acima para:
* InputStream is = new FileInputStream("arquivo.txt"); */
Scanner ent = new Scanner(is);
StringBuilder sb = new StringBuilder();
//int i = 1; // Contador de linhas do arquivo
i = 1; //////////////////////////////////////////////////////////
int il = 0; // Contador para índice do ArrayList
boolean ed = false; // Flag verif. se extraiu a data
boolean ee = false; // Flag verif. se extraiu os encargos
boolean e_cab = true; // Flag que indica que estamos nas linhas do cabeçalho
int tam; // Tamanho do arquivo texto bruto ( extraído do PDF )
int qi; // Quantidade total de insumos
dados1.SetAnd(0);
tam = new StringTokenizer(dados1.GetTE(), System.getProperty("line.separator"), false).countTokens();
dados1.SetTamAt(tam);
/* Em caso de mudança na formatação do SINAPI, basta mudar *
* o loop abaixo e a função "verIns" */
while (ent.hasNextLine()) {
String st = ent.nextLine();
st = st.trim();
if (!st.equals("")) { /* if (st.trim() != "") -> não funciona */
/* Extrai a data */
if (ed == false && st.length() == 7) {
if (st.charAt(2) == '/' &&
Character.isDigit(st.charAt(1)) &&
Character.isDigit(st.charAt(3))) {
dados1.SetData(st);
ed = true;
}
}
/* Extrai os encargos sociais */
if (ee == false && st.startsWith("Encargos Sociais (%):")) {
dados1.SetEnSo(st.substring(21).trim());
ee = true;
}
if (st.equals("PREÇOS DE INSUMOS")) { // Flag - Início de linhas do cabeçalho
e_cab = true;
}
/* Extrai os campos de cada Insumo */
if (e_cab == false) { // Se não estiver em linhas de cabeçalho...
if (!verIns(st).codi.equals("")) { // Se for linha que contém insumo...
ArIn.add(verIns(st));
il++;
} else {
if (!st.startsWith("Total de Insumos:")) { // Se não for a última linha...
ArIn.get(il - 1).desc += " " + st; // Acrescenta a continuação da
} // descrição ( da outra linha )
}
}
if (st.equals("Código Descriçao do Insumo Unid PreçoMediano (R$)")) {
e_cab = false; // Flag - Fim de linhas do cabeçalho
}
}
i++;
/////////////////////////////////////////////
setProgress(Math.min(100 / 6904 * i, 100));
try {
Thread.sleep(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("estou no loop !" + i);
/////////////////////////////////////////////
dados1.SetAnd(i);
}
/* Varre todo o ArrayList de Insumos para armazená-los no StringBuffer */
for (Insumo Ins : ArIn) {
sb.append(Ins.codi).append(Delim).
append(Ins.desc).append(Delim).
append(Ins.unid).append(Delim).
append(Ins.prec).append(System.getProperty("line.separator"));
}
qi = ArIn.size(); // Obtem a quantidade total de insumos
dados1.SetQti("" + qi); // Converte de "int" para "String"
return sb.toString(); // Retorna todos os insumos já processados
}
/* -------- Verifica se a linha corrente refere-se à insumo *
* *
* Se o membro "codi" do objeto retornado for string vazia "" *
* Então considera-se que a linha não é insumo *
* */
private Insumo verIns(String st) {
Insumo InsAux1 = new Insumo();
InsAux1.codi = "";
InsAux1.desc = "";
InsAux1.unid = "";
InsAux1.prec = "";
StringBuilder sb1 = new StringBuilder();
/* **** Critério 1 - Verifica o código ( deve conter 7 dígitos numéricos ) */
for (int i = 0; i <= 7; i++) {
if (!Character.isDigit(st.charAt(i))) {
return InsAux1; // Retorna com o objeto InsAux com membros vazios
} else {
sb1.append(st.charAt(i));
}
}
// InsAux1.codi = sb1.toString(); /* -> Se quiser o Código com zeros à esquerda */
InsAux1.codi = Integer.parseInt(sb1.toString()) + ""; /* Faz a conversão entre os tipos
para eliminar os zeros à esquerda */
/* **** Critério 2 - Verifica se o próximo caracter é um espaço */
if (st.charAt(8) != ' ') {
return InsAux1; // Retorna com o objeto InsAux com membros vazios
}
/* **** Localiza o próximo espaço após o campo unidade e Captura este campo */
int pos = st.indexOf(' ', 9);
InsAux1.unid = st.substring(9, pos);
/* **** Extrai o preço unitário */
int a = st.indexOf(',', pos);
InsAux1.prec = st.substring(pos + 1, a + 3); // Dois dígitos após a vírgula
/* **** Extrai a descrição */
InsAux1.desc = st.substring(a + 3, st.length());
return InsAux1; // Retorna um objeto "Insumo" já com os dados alimentados
}
@Override
protected Dados doInBackground() throws Exception {
System.out.println("entrei no PROCESSA 1 !");
processa();
System.out.println("entrei no PROCESSA 2!");
if (!isCancelled()) {
return dados1;
} else {
return null;
}
}
//@Override
protected void process() {
setProgress(i);
}
@Override
protected void done() {
//Dados dados1 = null;
try {[color=blue] [/color]
//dados1 = get(); // -> não precisou
get();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("entrei no DONE() !");
}
}
Alguém saberia me dizer o que há de errado?