Bom dia galera da GUJ! Em um ato desesperador é que peço vossa ajuda, estou preso em tal problema há UMA SEMANA (faz hoje), e agora é que complicou de vez. Pois bem, a princípio eu só queria uma jProgressBar que contasse o tempo de um determinado processo, depois resolvi que seria um contador que iria rodar em uma thread... eu não sabia como usava thread então fui estudar; logo mais, vi um tópico aqui no GUJ que falava de Observer e Observable, lá vai eu estudar denovo e tentar implementar. OK, aprendi isso e implementei numa classe A PARTE do meu programa, APENAS para testes... e lá funcionou, agora quando eu tento adaptar no meu programa, FAZENDO EXATAMENTE A MESMA COISA, o JFrame abre de forma estranha, como se por dentro ficasse invisível. O Mais estranho, é que se eu chamo esse objeto(GUI) de QUALQUER canto do meu programa, acontecerá a mesma coisa; porém se eu chamo lá da classe que eu criei apenas para testes, ela funciona PERFEITAMENTE.
O que eu faço é o Seguinte: Eu instancio uma classe GUI, que tem um frame com uma label Contador, lanço uma thread com um processo em um objeto observable, a cada iteração no run() eu notifico os Observers (Classe GUI) e incremento minha Label contadora.
Segue o código da minha classe TESTE:
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Observable;
import modelo.Item;
import modelo.ObjetoPublico;
import visualizacao.ContadorProgresso;
/**
*
* @author HTS
*/
public class NewClass{
static MeuObservable ob;
static ContadorProgresso cp;
public MeuObservable getOb() {
return ob;
}
public NewClass(){
ob = new MeuObservable();
cp = new ContadorProgresso("Teste.txt",this);
}
public static void main(String arg[]){
new NewClass();
}
public class MeuObservable extends Observable implements Runnable{
public void changeSome(){
setChanged();
notifyObservers();
}
public void run() {
BufferedReader cargaPLU = Conexao.arqCargaCod();
boolean erro;
if (cargaPLU == null) {
erro = false;
}
String codBarra = "", quantidade = "", descricao = "", codInterno = "", tipoProd = "";
try {
while (cargaPLU.ready()) {
String linha = cargaPLU.readLine();
for (int i = 0; i < linha.length(); i++) {
ob.changeSome();
Item item = new Item();
codBarra = "";
quantidade = "";
descricao = "";
codInterno = "";
tipoProd = "";
while (i < 13) {
codBarra += linha.charAt(i);
i++;
}
while (i < 22) {
quantidade += linha.charAt(i);
i++;
}
while (i < 47) {
descricao += linha.charAt(i);
i++;
}
while (i < 53) {
codInterno += linha.charAt(i);
i++;
}
while (i < 54) {
tipoProd += linha.charAt(i);
i++;
}
//item.setDigitoVerificador(String.valueOf(codBarra.charAt(12))); Isso fica para depois.
item.setCodigoBarra(codBarra); // para excluir o digito verificador: Usar 0~12
item.setCodigoInterno(codInterno);
item.setQuantidade(quantidade);
item.setTipoProd(tipoProd);
ObjetoPublico.getCargaCod().add(item);
// System.out.println("CodBarra - "+item.getCodigoBarra()+" Qnt - "+item.getQuantidade()+" descrição - "+item.getDescricao()+" codInterno - "+item.getCodigoInterno()+" tipo PRod - "+item.getTipoProd());
}
}
//cp.done();
} catch (IOException e) {
erro = false;
}
erro = true;
}
}
}
/*Fim da classe de teste*/
Segue a minha função GUI (Observer)
import dao.ItemDAO.*;
import dao.NewClass;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* @author HTS
*/
public class ContadorProgresso extends javax.swing.JFrame implements Observer{
private int contador = 1;
public void setLabelArquivo(JLabel LabelArquivo) {
this.LabelArquivo = LabelArquivo;
}
public void setLabelCont(JLabel LabelCont) {
this.LabelCont = LabelCont;
}
public JLabel getLabelArquivo() {
return LabelArquivo;
}
public JLabel getLabelCont() {
return LabelCont;
}
/** Creates new form ContadorProgresso */
public ContadorProgresso(String nomeArquivo, Object a) {
initComponents();
setLocationRelativeTo(null);
getLabelArquivo().setText(nomeArquivo);
setVisible(true);
JFrame frame2 = this;
if(a instanceof NewClass){
NewClass nc = (NewClass) a;
nc.getOb().addObserver(this);
nc.getOb().run();
} else if(a instanceof ObserverArqCod){
repaint();
ObserverArqCod ob = (ObserverArqCod) a;
ob.addObserver(this);
ob.run();
}
}
/** 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() {
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
LabelArquivo = new javax.swing.JLabel();
LabelCont = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel2.setFont(new java.awt.Font("Calibri", 1, 12));
jLabel2.setText("Arquivos Carregados");
jLabel3.setFont(new java.awt.Font("Calibri", 1, 13));
jLabel3.setText("Carregando o Arquivo ");
LabelArquivo.setFont(new java.awt.Font("Calibri", 1, 13));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(LabelCont, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(LabelArquivo, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE))
.addContainerGap(22, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(LabelArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(LabelCont, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(36, 36, 36))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify
private javax.swing.JLabel LabelArquivo;
private javax.swing.JLabel LabelCont;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
// End of variables declaration
public void atualiza(){
getLabelCont().setText(String.valueOf(contador));
contador++;
pack();
validate();
repaint();
}
public void done(){
dispose();
}
public void update(Observable o, Object arg) {
System.out.println("Contador = "+contador+"Objeto Observável - "+o.toString());
//JOptionPane.showMessageDialog(null,contador); teste
atualiza();
}
}
/*Fim da classe GUI*/
AGORA, Um Canto que eu tento chamar tal objeto GUI e ele instancia de forma errada (Não acusando nenhuma exception)
private boolean carregaArqCod(){
BufferedReader cargaPLU = Conexao.arqCargaCod();
ob = new ObserverArqCod(cargaPLU);
cp = new ContadorProgresso("Teste.txt",ob);
return ob.isErro();
}
Segue a private classe ObserverArqCod
public class ObserverArqCod extends Observable implements Runnable{
private boolean erro;
private BufferedReader cargaPLU;
public boolean isErro() {
return erro;
}
public ObserverArqCod(BufferedReader cPLU){
cargaPLU = cPLU;
}
public void changeSome(){
setChanged();
notifyObservers();
}
public void run() {
if (cargaPLU == null) {
erro = false;
}
String codBarra = "", quantidade = "", descricao = "", codInterno = "", tipoProd = "";
try {
while (cargaPLU.ready()) {
String linha = cargaPLU.readLine();
for (int i = 0; i < linha.length(); i++) {
ob.changeSome();
Item item = new Item();
codBarra = "";
quantidade = "";
descricao = "";
codInterno = "";
tipoProd = "";
while (i < 13) {
codBarra += linha.charAt(i);
i++;
}
while (i < 22) {
quantidade += linha.charAt(i);
i++;
}
while (i < 47) {
descricao += linha.charAt(i);
i++;
}
while (i < 53) {
codInterno += linha.charAt(i);
i++;
}
while (i < 54) {
tipoProd += linha.charAt(i);
i++;
}
//item.setDigitoVerificador(String.valueOf(codBarra.charAt(12))); Isso fica para depois.
item.setCodigoBarra(codBarra); // para excluir o digito verificador: Usar 0~12
item.setCodigoInterno(codInterno);
item.setQuantidade(quantidade);
item.setTipoProd(tipoProd);
ObjetoPublico.getCargaCod().add(item);
// System.out.println("CodBarra - "+item.getCodigoBarra()+" Qnt - "+item.getQuantidade()+" descrição - "+item.getDescricao()+" codInterno - "+item.getCodigoInterno()+" tipo PRod - "+item.getTipoProd());
}
}
//cp.done();
} catch (IOException e) {
erro = false;
}
erro = true;
}
}
Note que eu faço a mesma coisa em ambos casos, no entanto o frame fica "invisível" em um dos casos, como segue o print:
http://imageshack.us/f/38/semttuloaay.png/
Muito Obrigado pessoal!!

