package jfilechooserdemo.resources;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
class MyCustomFilter extends javax.swing.filechooser.FileFilter {
@Override
public boolean accept(File file) {
// Allow only directories, or files with ".xml" extension
return file.isDirectory() || file.getAbsolutePath().endsWith(".xml");
}
@Override
public String getDescription() {
// This description will be displayed in the dialog,
// hard-coded = ugly, should be done via I18N
return "Arquivos XML (*.xml)";
}
}
public class JFileChooserDemo extends javax.swing.JFrame {
private static String filePath;
/**
* Creates new form JFileChooserDemo
*/
public JFileChooserDemo() {
initComponents();
}
/**
* 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() {
fileChooser = new javax.swing.JFileChooser();
jScrollPane1 = new javax.swing.JScrollPane();
textarea = new javax.swing.JTextArea();
jLabel3 = new javax.swing.JLabel();
txtRazaoSocial = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtNumeroNF = new javax.swing.JTextField();
jScrollPane2 = new javax.swing.JScrollPane();
tblConferencia = new javax.swing.JTable();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
Open = new javax.swing.JMenuItem();
Exit = new javax.swing.JMenuItem();
fileChooser.setDialogTitle("This is my open dialog");
fileChooser.setFileFilter(new MyCustomFilter());
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Demo application");
setResizable(false);
textarea.setColumns(20);
textarea.setRows(5);
jScrollPane1.setViewportView(textarea);
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel3.setText("Razão Social");
jLabel3.setMaximumSize(new java.awt.Dimension(77, 15));
jLabel3.setMinimumSize(new java.awt.Dimension(77, 15));
jLabel3.setPreferredSize(new java.awt.Dimension(77, 15));
txtRazaoSocial.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtRazaoSocialActionPerformed(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel4.setText("Número NF-e");
tblConferencia.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},
{null, null}
},
new String [] {
"Descrição do Produto", "Quantidade"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.Integer.class
};
boolean[] canEdit = new boolean [] {
false, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tblConferencia.getTableHeader().setResizingAllowed(false);
tblConferencia.getTableHeader().setReorderingAllowed(false);
jScrollPane2.setViewportView(tblConferencia);
if (tblConferencia.getColumnModel().getColumnCount() > 0) {
tblConferencia.getColumnModel().getColumn(0).setResizable(false);
tblConferencia.getColumnModel().getColumn(0).setPreferredWidth(300);
tblConferencia.getColumnModel().getColumn(1).setResizable(false);
}
jMenu1.setText("File");
Open.setText("Open");
Open.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OpenActionPerformed(evt);
}
});
jMenu1.add(Open);
Exit.setText("Exit");
Exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExitActionPerformed(evt);
}
});
jMenu1.add(Exit);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 582, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(txtNumeroNF, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(txtRazaoSocial)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtRazaoSocial, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtNumeroNF, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
//Fonte do exemplo: https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
if (!file.getName().endsWith(".xml")) {
throw new IOException("Arquivo com extensão inválida.");
}
filePath = file.getAbsolutePath();
Document doc = getDoc(filePath);
String razaoSocial = getTagValue(doc, "dest", "xNome");
String numeroNFe = getTagValue(doc, "ide", "nNF");
txtRazaoSocial.setText(razaoSocial);
txtNumeroNF.setText(numeroNFe);
//String tblConferencia = getTagValue(0,1);
NodeList produtos = getElementsByTagName(doc, "det", "prod");
//o que retorna aqui com 2 produtos?
int qtdProdutos = produtos.getLength();
//quantidade de linhas
int qtdLinhas = tblConferencia.getRowCount();
//se a quantidade de produtos for diferente da quantidade de linhas
if (qtdLinhas != qtdProdutos) {
//JOptionPane.showMessageDialog(null,"lina= "+linha);
//double tblConferencia = getColumnClass(int columnIndex);
//setValueAt(Object value,int rowIndex,int columnIndex);
//adicionar ou remover a diferença da quantidade de linhas
//pesquisar JTable add row ou remove row
}
//Percorrer a lista de produtos e escrever a descricao xProd
//for (int indiceDaLinhaAtual = 0; indiceDaLinhaAtual < produtos.getLength(); indiceDaLinhaAtual++) {;
//
// Node nNode = nList.item(temp);
//
// System.out.println("\nCurrent Element :" + nNode.getNodeName());
//
// if (nNode.getNodeType() == Node.ELEMENT_NODE) {
//
// Element eElement = (Element) nNode;
//
// Definir valores
// String descricao = eElement.getElementsByTagName("xProd").item(0).getTextContent()
// tblConferencia.setValueAt(descricao, indiceDaLinhaAtual, 0);
// System.out.println("Staff id : " + eElement.getAttribute("id"));
// System.out.println("First Name : " + );
// System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
// System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
// System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
//
// }
//}
//botao conferir
//ler o arquivo Document doc = getDoc(filePath);
//pegar os valores das linhas e validar se estão válidos maior que zero e batendo com os do XML em
// NodeList produtos = getElementsByTagName(doc, "det", "prod");
//se tudo estiver válido, notificar na textarea ou algo do tipo
} catch (IOException ex) {
textarea.setText(
"Erro ao acessar o arquivo: "
+ file.getAbsolutePath()
+ "\nDetalhe: "
+ ex.getMessage());
} catch (SAXException | ParserConfigurationException ex) {
Logger.getLogger(JFileChooserDemo.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
System.out.println("File access cancelled by user.");
}
}
private Document getDoc(String filePath)
throws
FileNotFoundException,
SAXException,
IOException,
ParserConfigurationException {
File fXmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
return doc;
}
private String getTagValue(
Document doc,
String elementoPai,
String elementoFilho) throws DOMException {
String textContent = "";
textContent = getElementsByTagName(doc, elementoPai, elementoFilho).
item(0)
.getTextContent();
System.out.println("TAG content: " + textContent);
return textContent;
}
private NodeList getElementsByTagName(Document doc, String elementoPai, String elementoFilho) {
NodeList nList = doc.getElementsByTagName(elementoPai);
System.out.println("----------------------------");
Node nNode = nList.item(0);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
NodeList elements = eElement
.getElementsByTagName(elementoFilho);
return elements;
}
return nList;
}
private void ExitActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void txtRazaoSocialActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* @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;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(JFileChooserDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JFileChooserDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JFileChooserDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JFileChooserDemo.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 JFileChooserDemo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem Exit;
private javax.swing.JMenuItem Open;
private javax.swing.JFileChooser fileChooser;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable tblConferencia;
private javax.swing.JTextArea textarea;
private javax.swing.JTextField txtNumeroNF;
private javax.swing.JTextField txtRazaoSocial;
// End of variables declaration
}
preciso trazer a descrição do produto do XML da NFe. a coluna quantidade deve ficar vazia para que eu possa editar o valor para fazer a conferência com o xml da nata pra ver se vai bater a quantidade.
preciso de ajuda.
[quote="Divino69, post:1, topic:388073"]
//for (int indiceDaLinhaAtual = 0; indiceDaLinhaAtual < produtos.getLength(); indiceDaLinhaAtual++) {;
//
// Node nNode = nList.item(temp);
//
// System.out.println("\nCurrent Element :" + nNode.getNodeName());
//
// if (nNode.getNodeType() == Node.ELEMENT_NODE) {
//
// Element eElement = (Element) nNode;
//
// Definir valores
// String descricao = eElement.getElementsByTagName("xProd").item(0).getTextContent()
// tblConferencia.setValueAt(descricao, indiceDaLinhaAtual, 0);
// System.out.println("Staff id : " + eElement.getAttribute("id"));
// System.out.println("First Name : " + );
// System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
// System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
// System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
//
// }
[/quote]
Neste ponto acho que poderia fazer o seguinte:
for (int indiceDaLinhaAtual = 0; indiceDaLinhaAtual < produtos.getLength(); indiceDaLinhaAtual++) {;
Node nNode = produtos.item(indiceDaLinhaAtual);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
// Definir valores
String descricao = eElement.getElementsByTagName("xProd").item(0).getTextContent();
jTableConferencia.setValueAt(descricao, indiceDaLinhaAtual, 0);
// System.out.println("Staff id : " + eElement.getAttribute("id"));
// System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
// System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
// System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
// System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
}
}
Preciso criar um botão conferir vc pode me dar uma dica?
for (int indiceDaLinhaAtual = 0; indiceDaLinhaAtual < produtos.getLength(); indiceDaLinhaAtual++) {
Node nNode = produtos.item(indiceDaLinhaAtual);
System.out.println("\nCurrent Element :" +
produtos.item(indiceDaLinhaAtual).getTextContent());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
//indiceDaLinhaAtual
Element eElement = (Element) nNode;
//Definir valores
String descricao = eElement.getElementsByTagName("xProd").item(0).getTextContent();
tblConferencia.setValueAt(descricao, indiceDaLinhaAtual, 0);
System.out.println("ide : " + eElement.getAttribute("nNF"));
System.out.println("prod : " + eElement.getElementsByTagName("xProd").item(0).getTextContent());
System.out.println("Amount Quantidade : " + eElement.getElementsByTagName("amountquantidade").item(0).getTextContent());
// System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
// System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
}
}
//botao conferir
//ler o arquivo Document doc = getDoc(filePath);
//pegar os valores das linhas e validar se estão válidos maior que zero e batendo com os do XML em
//Node produtos = getElementsByTagName(doc, "det", "xProd");
//se tudo estiver válido, notificar na textarea ou algo do tipo
} catch (IOException ex) {
textarea.setText(
"Erro ao acessar o arquivo: "
+ file.getAbsolutePath()
+ "\nDetalhe: "
+ ex.getMessage());
} catch (SAXException | ParserConfigurationException ex) {
Logger.getLogger(JFileChooserDemo.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
System.out.println("File access cancelled by user.");
}
}
Neste ponto acho que poderia fazer o seguinte:
for (int indiceDaLinhaAtual = 0; indiceDaLinhaAtual < produtos.getLength(); indiceDaLinhaAtual++) {;
Node nNode = produtos.item(indiceDaLinhaAtual);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
// Definir valores
String descricao = eElement.getElementsByTagName("xProd").item(0).getTextContent();
jTableConferencia.setValueAt(descricao, indiceDaLinhaAtual, 0);
// System.out.println("Staff id : " + eElement.getAttribute("id"));
// System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
// System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
// System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
// System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
}
}
[/quote]