Erro no setvisible(true) {interessante}[RESOLVIDO]

10 respostas
M

galera eu tenho Jframes com nomes Imagem1, imagem2 e imagem3 tudo no mesmo pacote chamado apresentacao
mas quando ou crio um objeto da imagem2 ne imagem1 ele dá o seginte erro quando mando rodar.(inclusive esse erro já dá na primeira tela do meu programa alguem mim ajuda por favor o erro é...

Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at sun.awt.Win32GraphicsConfig.getBounds(Native Method)
at sun.awt.Win32GraphicsConfig.getBounds(Win32GraphicsConfig.java:215)
at java.awt.Window.init(Window.java:393)
at java.awt.Window.(Window.java:432)
at java.awt.Frame.(Frame.java:403)
at java.awt.Frame.(Frame.java:368)
at javax.swing.JFrame.(JFrame.java:163)
at Apresentacao.Imagem2.(Imagem2.java:25)
at Apresentacao.Imagem1.(Imagem1.java:19)
at Apresentacao.Imagem2.(Imagem2.java:21)
at Apresentacao.Imagem1.(Imagem1.java:19)
at Apresentacao.Imagem2.(Imagem2.java:21)
at Apresentacao.Imagem1.(Imagem1.java:19)
at Apresentacao.Imagem2.(Imagem2.java:21)
at Apresentacao.Imagem1.(Imagem1.java:19)

e em quanto ele não termina de construir esse erro parece uma dizima alguem mim explica....

aki em baixo é onde eu tó tentando criar o objeto

public class Imagem1 extends javax.swing.JFrame {

    Imagem2 I2 = new Imagem2();

    /** Creates new form Imagem1 */
    public Imagem1() {
        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() {

        jLabel1 = new javax.swing.JLabel();
        jBProxima = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/More-Chan.jpg"))); // NOI18N

        jBProxima.setText("Proxima");
        jBProxima.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBProximaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(386, Short.MAX_VALUE)
                .addComponent(jBProxima)
                .addGap(361, 361, 361))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBProxima)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void jBProximaActionPerformed(java.awt.event.ActionEvent evt) {
        this.I2.setVisible(true);
    }

10 Respostas

V

Por favor, poste as linha 25 do arquivo Imagem2.java e a linha 19 do Imagem1.java.

Provavelmente, nessas linhas, uma classe está chamando a outra.

M

O que eu quero fazer é o seguinte eu tenho a tela Imagem1 quando clica no jBProxima o programa abra a tela Imagem2 e feche a Imagem1 porem assim sucessivamente até quando eu quiser ir pra próxima e fechar a janela que estava.

Entendeu?

Oi mano segue o código completo aí ó..
// este é minha tela de login onde já começa a dar o erro

package Apresentacao;

import javax.swing.JOptionPane;

/**
 *
 * @author Milar Flores
 */
public class WelcomeLogin extends javax.swing.JFrame {

    TelaInicial TI = new TelaInicial();
    
    public void boasvindas() {
        JOptionPane.showMessageDialog(null, "                              SEJA BEM VINDO" + "\n" + "Informe seu nome de usuário e senha, na poxima janela.");
    }

    public void verificaComponentes() {
        boolean aux = false;
        if (this.jTUsuario.getText().equals("")) {
            aux = true;
        } else if (this.jPSenha.getText().equals("")) {
            aux = true;
        }
        if (aux == true) {
            JOptionPane.showMessageDialog(null, "Por Favor insira o usuário juntamente a senha.");
        }
    }

    public void verificaUsuario() {
        boolean aux = false;
        boolean aux2 = false;

        if  (this.jTUsuario.getText().equals("guj")) {
            aux = true;
        }
        if (this.jPSenha.getText().equals("gujguj")){
            aux2 = true;
        }
        if (aux == false || aux2 == false) {
            JOptionPane.showMessageDialog(null, "Usuário ou senha incorretos.");
        }
        if (aux == true && aux2 == true) {
            this.TI.setVisible(true);
        }
    }

    public void fechaTela() {
        this.dispose();
    }

    /** Creates new form WelcomeLogin */
    public WelcomeLogin() {
        initComponents();
        this.boasvindas();
    }

    /** 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();
        jLabel1 = new javax.swing.JLabel();
        jTUsuario = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jPSenha = new javax.swing.JPasswordField();
        jBlogin = new javax.swing.JButton();
        jBLimpar = new javax.swing.JButton();
        jBSair = new javax.swing.JButton();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "LOGIN", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        jLabel1.setText("Usuário:");

        jLabel2.setText("Senha:");

        jBlogin.setText("Login");
        jBlogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBloginActionPerformed(evt);
            }
        });

        jBLimpar.setText("Limpar");
        jBLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBLimparActionPerformed(evt);
            }
        });

        jBSair.setText("Sair");
        jBSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBSairActionPerformed(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, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPSenha))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jBlogin)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jBLimpar)
                        .addGap(18, 18, 18)
                        .addComponent(jBSair)))
                .addContainerGap(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(jLabel1)
                    .addComponent(jTUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jPSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBlogin)
                    .addComponent(jBSair)
                    .addComponent(jBLimpar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(12, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jBloginActionPerformed(java.awt.event.ActionEvent evt) {                                        
        this.verificaComponentes();
        this.verificaUsuario();
        this.jTUsuario.setText("");
        this.jPSenha.setText("");
        this.fechaTela();
    }                                       

    private void jBLimparActionPerformed(java.awt.event.ActionEvent evt) {                                         
        this.jTUsuario.setText("");
        this.jPSenha.setText("");
    }                                        

    private void jBSairActionPerformed(java.awt.event.ActionEvent evt) {                                       
        this.dispose();
    }                                      

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new WelcomeLogin().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jBLimpar;
    private javax.swing.JButton jBSair;
    private javax.swing.JButton jBlogin;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPasswordField jPSenha;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTUsuario;
    // End of variables declaration                   

}
// este é o jFrame Imagem1
package Apresentacao;

/**
 *
 * @author Milar Flores
 */
public class Imagem1 extends javax.swing.JFrame {

    Imagem2 I2 = new Imagem2();

    /** Creates new form Imagem1 */
    public Imagem1() {
        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() {

        jLabel1 = new javax.swing.JLabel();
        jBProxima = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/More-Chan.jpg"))); // NOI18N

        jBProxima.setText("Proxima");
        jBProxima.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBProximaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(386, Short.MAX_VALUE)
                .addComponent(jBProxima)
                .addGap(361, 361, 361))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBProxima)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jBProximaActionPerformed(java.awt.event.ActionEvent evt) {                                          
        this.I2.setVisible(true);
        this.dispose();
    }                                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Imagem1().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jBProxima;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}
//este o jFrame Imagem2

package Apresentacao;

/**
 *
 * @author Milar Flores
 */

public class Imagem2 extends javax.swing.JFrame {

    Imagem1 I1 = new Imagem1();
    Imagem3 I3 = new Imagem3();

    /** Creates new form Imagem2 */
    public Imagem2() {
        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() {

        jLabel1 = new javax.swing.JLabel();
        jBAnterior = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/More-Chan (1).jpg"))); // NOI18N

        jBAnterior.setText("Anterior");
        jBAnterior.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBAnteriorActionPerformed(evt);
            }
        });

        jButton2.setText("Proxima");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(103, 103, 103)
                        .addComponent(jBAnterior)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 508, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBAnterior)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void jBAnteriorActionPerformed(java.awt.event.ActionEvent evt) {                                           
        this.I1.setVisible(true);
    }                                          

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        this.I3.setVisible(true);
        this.dispose();
    }                                        

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Imagem2().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jBAnterior;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   

}
V

Bom, na classe Imagem1 vc faz new Imagem2(), na classe Imagem2 você faz new Imagem1().

Desse jeito, uma vai ficar criando a outra eternamente.

M

Então man eu preciso desses métodos para fazer o setvisible ou existe outra maneira?

eu posso usar isso?
importar a classe Imagem2 e usar o método

public Imagem2() { initComponents(); }

isso é um método né de iniciar componentes será que teria como eu usar isso lá para iniciar a janela chamando no butão jBProximo da janela Imagem1

V

Você pode passar uma classe como parâmetro da outra:

public class Imagem2 {
  private Imagem1 imagem1;

  public Imagem2(Imagem1 imagem1) {
      this.imagem1 = imagem1;
   }
    //...
}
E, na classe imagem 1:
public class Imagem1 {
    public Imagem2 imagem2 = new Imagem2(this);
    //...
}

Assim imagem 1 cria imagem 2, mas imagem 2 apenas usa imagem 1.

M

vey vc é cranio vlw

M

Aì como eu crio lista de imagens e chamo elas atravez de metodos para muda-las no jLable e substitui-las

S

Me corrijam se etiver errado mas você poderia fazer uma array de string (ou qualquer outro modo de armazenamento tanto em memoria quanto em banco) com a localização das imagens que deseja adicionar no JLabel, usando o metodo abaixo é possivel chama-los pela String exibindo o na tela, desculpe se não fui muito claro.

jlabel.setIcon(new ImageIcon("o caminho para a imagem vai aqui"));
M

cara vc foi claro mais eu preciso estudar mais para entender de cara…
eu eu odeio vetores ARRAY mais é o jeito

S

Bom se o problema é array aki tem um tuto

http://www.plugmasters.com.br/sys/materias/535/1/Arrays-em-Java

mas o tipo de armazenamento depende muito do que você precisa, se já sabe a quantidade que vai precisar e vai apenas adicionar e alterar os valores sem remover o mais indicado é o array, senão o mais indicado são objetos (classes java) que fazem o papel de administração no armazenamento que há também de varios formatos o armazenamento em nuvem por exemplo, que facilita a exclusão de objetos no entanto há mais demora para pesquisar objetos (sendo assim para alterar) pois se houver 100.000 objetos nessa lista a pesquisa irá começar por exemplo do primeiro até encontrar o correto ou o mesmo processo só que do ultimo para o primeiro.

Alguns Exemplos de Listas

ArrayList - ele usa array por debaixo dos panos
http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html

LinkedList - no formato nuvem, como se os objetos armazenos estivessem linkados em sequencia
http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedList.html

Há outros modelos de armazenamento também da uma pesquisada ai que você encontra muita coisa :wink:

Criado 18 de dezembro de 2009
Ultima resposta 12 de jan. de 2010
Respostas 10
Participantes 3