JInternalFrame

Olá a todos!!

Gostaria de tirar a seguinte dúvida , tenho a seguinte estrutura:

-Jframe (principal) com um jDesktopPane (jDesktopPane1);
-2 JIinternalFrame (1-buttonsEnfermeiros , 2-cadEnfermeiros;
O primeiro jInternalFrame (buttonsEnfermeiros) possui botões que chamam outro JInternalFrame (cadEnfermeiros).

No action do botão cadastrar da classe buttonsEnfermeiros, coloquei o seguinte código:

principal p = new principal();  
cadEnfermeiros n = new cadEnfermeiros;  
p.jDesktopPane1.add(n);  
n.setVisible(true);  
principal p = new principal(); cadEnfermeiros n = new cadEnfermeiros;
 p.jDesktopPane1.add(n);
 n.setVisible(true);

Quando clico no botão não aparece erro nenhum e a cadEnfermeiros não abre no jDesktopPane que está no Jframe principal, procurei soluções no forum mais não consegui fazer funcionar, estou usando a plataforma Netbeans

  Alguem pode me Ajudar???
  Grato!!

Algumas dicas:

  • Chame internalFrame.setVisible(true) antes de chamar JDesktopPane.add(internalFrame);
  • Depois de chamar JDesktopPane.add(internalFrame), chame internalFrame.setSelected(true).

agora o código ficou assim:

principal p = new principal();
cadEnf n = new cadEnf();
n.setVisible(true);
p.jDesktopPane1.add(n);
  
 try{
           p.setSelected(true);
}
    catch(PropertyVetoException e){
             e.printStackTrace();
} 

Não aparece erro nenhum mais ainda não abriu.

Será que devo alterar algo na classe principal, lembrando que eu fui nas propriedades do jDesktopPane e alterei para public

Por que você está chamando “principal p = new principal()” várias vezes? Você precisa usar o objeto principal que já existe, em vez de criar um outro.

Cara sou novo em java você pode demonstar em código isso pra mim? Entendi o seu conceito só não sei como aplica-lo. Obrigado pela força Aee!!

voce setou o tamanho do seu internalFrame?

seuInternalFrame.setSize(800,600);

vou postar um codigo aqui para vcs, mas nao se acostumem

[code]//************************** VERIFICA SE UMA TELA ESTA ABERTA OU NAO******************************
package Interface.Tela.TelaPrincipal;

import javax.swing.*;
// rafael vinicius kuhn toebe
public class VerificaTelaAberta {

static boolean valor = false;

public VerificaTelaAberta() {
}

public static void setValorAoFecharTela(boolean valor) {
    VerificaTelaAberta.valor = valor;

}

public static Boolean verificaFrame(JDesktopPane jDesktopPane, JInternalFrame frame) {

    JInternalFrame[] results;
    results = jDesktopPane.getAllFrames();
    valor = false;
    for (int i = 0; i < results.length; i++) {
        if (results[i].equals(frame)) {
            valor = true;
            break;
        }
    }
    return valor;
}



public static void destroiInternalframe(JInternalFrame internalframe) {
    JInternalFrame[] results;
    results = TelaPrincipal.jpDesktop.getAllFrames();
    valor = false;
    for (int i = 0; i < results.length; i++) {
        if (results[i].equals(internalframe)) {
            internalframe.dispose();
            setValorAoFecharTela(false);
            break;
        }
    }
    TelaPrincipal.setInformacoes("Bem-Vindo ao S.M.I.C.S - Sistema de Gerenciamento de Fazendas Agricolas", 3);
}

}
[/code]

Cara essa é uma classe que controla o JDesktop certo? Tenho que fazer alguma chamada dela na classe principal ou nas JInternalFrame? Tenho que somente trocar o nome a classe telaprincipal pela minha? e a chamada dos jDesktop na classe JInternal contiuará da mesma maneira que fiz anteriormente? Desculpa a quantidade de perguntas é que sou meio cabaço ainda!

Grato

1- Cara essa é uma classe que controla o JDesktop certo?

Resp: sim e não, na verdade verifica se o internalframe esta add no desktopPane

2- Tenho que fazer alguma chamada dela na classe principal ou nas JInternalFrame?

sim, na tela principal, é algo do genero

3- jDesktop na classe JInternal contiuará da mesma maneira que fiz anteriormente?

sim vai ficar parecido

[code]if(VerificaTelaAberta.verificaFrame(seuDesktopPane, SeuJInternalFrame)== false){

TelaCadastro telaCad = new TelaCadastro();
seuDesktopPane.add(seuInternalframe);
seuInternalFrame.setVisible(true);
seuInternalframe.setSize(800,600);

}

[/code]

é apenas um exemplo mal feito mas da para entender hahahahhaha, a classe VerificaTelaAberta é o pulo do gato :smiley:

ola,

segue um exemplo vê se te serve, adiciona mais a classe que rafael criou e te diverte ai.

1 – JFrame Principal


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PrincipalJFrame.java
 *
 * Created on Mar 16, 2011, 2:00:48 PM
 */

package teste;

import java.beans.PropertyVetoException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JInternalFrame;

/**
 *
 * @author Jailes
 */
public class PrincipalJFrame extends javax.swing.JFrame {

    //Referencia para objeto singleton
    //Para pode pega a instancia e add internalframes 
    private static PrincipalJFrame instance = null;
        
    public static PrincipalJFrame getInstance(){
        if(instance == null){
            instance = new PrincipalJFrame();
        }
        return instance;
    } 
    
    /** Creates new form PrincipalJFrame */
    public PrincipalJFrame() {
        initComponents();        
        iniciaPrimeiroJIF();        
    }

    private void iniciaPrimeiroJIF(){        
        PrimeiroJInternalFrame pjif = new PrimeiroJInternalFrame();
        pjif.setVisible(true);        
        addInternalFrame(pjif);
    }

    //Metodo que ira adiciona internal frame no jdeskpane
    public void addInternalFrame(JInternalFrame jit){
        try {
            jDesktopPane.add(jit);
            jit.setSelected(true);
        } catch (PropertyVetoException ex) {
            Logger.getLogger(PrincipalJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    /** 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() {

        jDesktopPane = new javax.swing.JDesktopPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("JFrame Principal");

        jDesktopPane.setPreferredSize(new java.awt.Dimension(500, 400));
        getContentPane().add(jDesktopPane, java.awt.BorderLayout.CENTER);

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

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

    // Variables declaration - do not modify
   // JDesk a onde sera adicionados JInternalFRame
    private javax.swing.JDesktopPane jDesktopPane;
    // End of variables declaration

}

2 – Primeiro JInternal Frame

[/code][code]/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PrimeiroJInternalFrame.java
 *
 * Created on Mar 16, 2011, 2:01:19 PM
 */

package teste;

/**
 *
 * @author Jailes
 */
public class PrimeiroJInternalFrame extends javax.swing.JInternalFrame {

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

        jButton1 = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Primeiro JInternalFrame");

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        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(303, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(18, 18, 18))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(244, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        
        SegundoJInternalFrame sjif = new SegundoJInternalFrame();
        sjif.setVisible(true);
        
        
        PrincipalJFrame.getInstance().addInternalFrame(sjif);
        
    }


    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    // End of variables declaration

}

3 – Segundo JInternal Frame


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SegundoJInternalFrame.java
 *
 * Created on Mar 16, 2011, 2:01:36 PM
 */

package teste;

/**
 *
 * @author Jailes
 */
public class SegundoJInternalFrame extends javax.swing.JInternalFrame {

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

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Segundo JInternalFrame");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 394, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 278, Short.MAX_VALUE)
        );

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


    // Variables declaration - do not modify
    // End of variables declaration

}

At+,

Jailes

com o exemplo que o seliaj apresentou + a minha classe vceis não vão mais ter problemas com a parte de gerenciamento de telas…

lembrando, eu uso a minha classe dentro de um ActionListener 8)

Não contava com a sua astúcia!!! Deu certo, obrigado pela paciência!
Abraços

RESOLVIDO!

marcel sanches

por nada :smiley: