Estou criando um sistema de conferencia, usando XML de uma Nata Fiscal Eletrônica, para isso preciso colocar mais e um produto na linha descrição de produto do JTable, só consegui por um.
Como que faz para por mais de 1 lembrando os nos são do mesmo XML. Alguém sabe?
Nó do XML
.3 Esse e o código do projeto
package jfilechooserdemo.resources;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
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.swing.JOptionPane;
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.
*/
private void verificar() throws SAXException, FileNotFoundException, ParserConfigurationException {
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 valorXml = (String) getTagValue(doc, "prod", "qTrib");
int valorXml2 = Integer.parseInt(valorXml.substring(0, 0));
//System.out.println(valorXml2);
String valor = (String) tblConferencia.getValueAt(0, 0);
System.out.println("VALOR:"+ valor);
int valor2 =Integer.parseInt(valor);
//String mensagem="escreva a quantidade";
System.out.println( valorXml);
// int valor2 =Integer.parseInt(JOptionPane.showInputDialog("Digite o nome do produto!", "Digite aqui o NOME"));
// System.out.println("valor");
if (valor2 == valorXml2) {
JOptionPane.showMessageDialog(null, "Conferencia concluida com sucesso. ");
} else {
JOptionPane.showMessageDialog(null, "Quantidade Errada!!!");
}
} catch (IOException ex) {
textarea.setText(
"Erro ao acessar o arquivo: "
+ file.getAbsolutePath()
+ "\nDetalhe: "
+ ex.getMessage());
}
}
}
@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();
btnConferir = new javax.swing.JButton();
btnAnexar = new javax.swing.JButton();
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");
txtNumeroNF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNumeroNFActionPerformed(evt);
}
});
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},
{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
};
public Class getColumnClass(int columnIndex) {
return types [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);
}
btnConferir.setText("Conferir");
btnConferir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnConferirActionPerformed(evt);
}
});
btnAnexar.setText("Anexar");
btnAnexar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAnexarActionPerformed(evt);
}
});
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)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnAnexar)
.addGap(35, 35, 35)
.addComponent(btnConferir)
.addGap(64, 64, 64))
.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.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtNumeroNF, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnConferir)
.addComponent(btnAnexar)))
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 314, 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");
String descricaoProd = getTagValue(doc, "prod", "xProd");
// Node valFormaOutros = doc.getElementsByTagName("xProd").item(0);
tblConferencia.setValueAt(descricaoProd, 0, 0);
txtRazaoSocial.setText(razaoSocial);
txtNumeroNF.setText(numeroNFe);
NodeList produtos = getElementsByTagName(doc, "dest", "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) {
//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 = produtos.item(indiceDaLinhaAtual);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
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", "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 btnConferirActionPerformed(java.awt.event.ActionEvent evt) {
try {
verificar();
} catch (SAXException | FileNotFoundException | ParserConfigurationException ex) {
Logger.getLogger(JFileChooserDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void txtRazaoSocialActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnAnexarActionPerformed(java.awt.event.ActionEvent evt) {
try {
//botao conferir
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 = (Node) getElementsByTagName(doc, "det", "prod");
//se tudo estiver válido, notificar na textarea ou algo do tipo
} catch (SAXException | IOException | ParserConfigurationException ex) {
Logger.getLogger(JFileChooserDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void txtNumeroNFActionPerformed(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.JButton btnAnexar;
private javax.swing.JButton btnConferir;
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
}