JInternalFrame com retorno

10 respostas
java
I

Pesquisei aqui no fórum, mais ate agora não consegui resolver o problema, Tenho um JFrame principal que contém o JDesktop, dele eu consigo chamar um JInternalFrame FPais e preciso fazer uma pesquisa no JInternalFrame FPaisConsu, quando eu selecionar na tabela ele retorna o valor para o JInternalFrame FPais, para jogar esse valor no txtCodPais.

//Chama o JInternalFrame FPaisConsu

TelaPaisCons = new FPaisConsu(S);

jdpPrincipial.add(TelaPaisCons);

TelaPaisCons.setVisible(true);
//Onde coloco esse método para pega o retorno do JInternalFrame FPaisConsu

retorno = TelaPaisCons.getRetorno();

if(retorno.equals(""))

return;

PegaPais();

txtCodPais       .setText(fc.FormataCampo(String.valueOf(retorno), 4, 0));

Preciso da orientações dos mestres.

10 Respostas

I

Se alguém tiver alguma ideia, ficarei muito grato, pesquisei em vários site e ate agora não solucionei o problema.

D

Quem sabe se você descrever melhor o cenário, fique mais fácil para obter ajuda.
Você escreveu sua necessidade pela metade.

E? Daí? O que você consegue, ok. E o que não consegue?

I

O objetivo é o JInternalFrame FPais abrir o JInternalFrame FPaisConsu, Ok, pesquisa na tabela do FPaisConsu, Ok, selecionar o item na tabela e enviar o retorno para o JInternalFrame FPais, e lançar o retorno no txtCodPais.

D

Procure pelo pattern observer.

I

darlan_machado, conseguir o retorno, só não estou conseguindo é lançar os dados nos campos assim que fecha o JIternalFrame de Consulta.

D

Como você implementou o design observer?

I

darlan_machado ainda não implementei o pattern observer, vou ver como implemento ele no meu código.

V
  1. Crie um método atualizarDados no JInternalFrame FPais. Nele passe os dados que vc quer atualizar como parâmetro e faça a atualização.

  2. Passe o FPais como parâmetro para o construtor do FPaisConsu. Quando fechar o FPaisConsu, chame o método atualizarDados.

Você pode tornar isso mais flexível (se esse internalframe for usado por mais formulários) através do Pattern Observer, sugerido pelo Darlan. Nesse caso, você também terá que criar uma interface, FPaisConsuListener, com o método atualizarDados e fazer FPais implementar essa interface. Assim, FPaisConsu receberia a interface ao invés de FPais diretamente.

Esse processo  estava escrito no link que passei para você por mensagem privada:

<aside class="quote quote-modified" data-post="2" data-topic="234197">
  <div class="title">
    <div class="quote-controls"></div>
    <img alt="" width="20" height="20" src="/user_avatar/www.guj.com.br/vinigodoy/40/98426_2.png" class="avatar">
    <a href="https://www.guj.com.br/t/meu-primeiro-tutorial-passando-valores-para-outro-jframe/234197/2">Meu primeiro tutorial [Passando valores para outro JFrame]</a> <a class="badge-wrapper  bullet" href="/c/assuntos-gerais">Assuntos Gerais</a>
  </div>
  <blockquote>
    Por que não deixar a janela secundária ter um atributo do tipo JanelaPrincipal direto?  vc não precisa de cast. 
Na verdade, a melhor maneira de organizar essas duas janelas, sem acopla-las demais, seria através do padrão observer. 
Para isso: 

Crie uma interface que irá receber o evento da janela secundária:


public interface JanelaSecundariaListener {
   //No caso, esse método transmite um texto
   void textoDefinido(String texto);
} 

No lugar do método instância, crie um método para rece…
  </blockquote>
</aside>
V

IMPORTANTE: Não existem JInternalFrames modais. Se você quiser impedir que o FPais seja atualizado enquanto FPaisConsu estiver aberto, utilize um JDialog (eu inclusive recomendo fortemente que você use JDialogs modais nesse caso, pois seu método setVisible é bloqueante).

Você pode fazer com que o JDialog se “disfarce” de JInternalFrame adicionando as seguintes linhas no construtor seu:

setUndecorated(true); 
getRootPane().setWindowDecorationStyle(JRootPane.FRAME);

Essa alternativa também estava linkada no link que te passei por mensagem privada:

I

Vou postar meu código para ficar mais claro como estou fazendo!

JInternalFrame1

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package Tela;

/**
*

  • @author User
    */
    public class JInternalCadastro1 extends javax.swing.JInternalFrame{

    String retorno               = "";
    
    int    abriuJInter           = 0;
    
    JInternalConsulta3           JI3;
    

    /**

    • Creates new form JInternalCadastro1
      */
    public JInternalCadastro1() {
    
    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)
      
      // 
      
      private void initComponents() {
      
      jLabel1 = new javax.swing.JLabel();
      
      jLabel2 = new javax.swing.JLabel();
      
      txt1 = new javax.swing.JTextField();
      
      jTextField1 = new javax.swing.JTextField();
      
      btPesquisa = new javax.swing.JButton();
      
      setClosable(true);
      
      setMaximizable(true);
      
      setTitle(Cadastro 01);
      
      addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
      
      public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
      
      formInternalFrameActivated(evt);
      
      }
      
      public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
      
      formInternalFrameClosed(evt);
      
      }
      
      public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
      
      }
      
      public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
      
      }
      
      public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
      
      }
      
      public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
      
      }
      
      public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
      
      formInternalFrameOpened(evt);
      
      }
      
      });
      

      jLabel1.setFont(new java.awt.Font(“Tahoma”, 0, 36)); // NOI18N
      jLabel1.setText(“Cadastro 01”);

      jLabel2.setText(“Codigo 01”);

      btPesquisa.setText(Pesquisa);
      
      btPesquisa.addActionListener(new java.awt.event.ActionListener() {
      
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      
      btPesquisaActionPerformed(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(210, Short.MAX_VALUE)
      
      .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)
      
      .addGap(250, 250, 250))
      
      .addGroup(layout.createSequentialGroup()
      
      .addContainerGap()
      
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
      
      .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      
      .addComponent(txt1))
      
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
      
      .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
      
      .addGap(96, 96, 96)
      
      .addComponent(btPesquisa)
      
      .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
      
      );
      
      layout.setVerticalGroup(
      
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      
      .addGroup(layout.createSequentialGroup()
      
      .addGap(28, 28, 28)
      
      .addComponent(jLabel2)
      
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
      
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
      
      .addComponent(txt1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
      
      .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
      
      .addComponent(btPesquisa))
      
      .addGap(117, 117, 117)
      
      .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
      
      .addContainerGap(194, Short.MAX_VALUE))
      
      );
      

      pack();
      }//

    private void btPesquisaActionPerformed(java.awt.event.ActionEvent evt) {
    
    abriuJInter = 1;
    
    JI3 = new JInternalConsulta3(S);
    
    getParent().add(JI3);
    
    JI3.setVisible(true);
    
    }
    

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {

    }

    private void formInternalFrameClosed(javax.swing.event.InternalFrameEvent evt) {

    }

    private void formInternalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
    
    if(abriuJInter == 0){
    
    return;
    
    }
    
    abriuJInter = 0;
    
    retorno = JI3.getRetorno();
    
    System.out.println(retorno 1 = +retorno);
    
    if(retorno.equals(””)){
    
    return;
    
    }
    
    txt1.setText(retorno);
    
    }
    
    // Variables declaration - do not modify
    
    private javax.swing.JButton btPesquisa;
    
    private javax.swing.JLabel jLabel1;
    
    private javax.swing.JLabel jLabel2;
    
    private javax.swing.JTextField jTextField1;
    
    private javax.swing.JTextField txt1;
    
    // End of variables declaration
    

}

JInternalFrame2

package Tela;

public class JInternalConsulta3 extends javax.swing.JInternalFrame {

String somostra             = "";
String retorno              = "";

int    linha                = 0;
 
/**
 * Creates new form JInternalCadastro1
 */
public JInternalConsulta3(String Somostra){
    somostra                = Somostra;
    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();
    jScrollPane1 = new javax.swing.JScrollPane();
    tabela_consulta = new javax.swing.JTable();
    Bt4 = new javax.swing.JButton();
    btEnviar = new javax.swing.JButton();

    setClosable(true);
    setMaximizable(true);
    setTitle("Pesquisa 03");

    jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
    jLabel1.setText("Consulta 03");

    tabela_consulta.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {"1", "Maria", "Rua 1", null},
            {"2", "Jose", "Rua 3", null},
            {"3", "Joao", "Rua 1", null},
            {"4", "Ana", "Rua 2", null}
        },
        new String [] {
            "Title 1", "Title 2", "Title 3", "Title 4"
        }
    ) {
        boolean[] canEdit = new boolean [] {
            false, false, false, false
        };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    jScrollPane1.setViewportView(tabela_consulta);

    Bt4.setText("Cadastro 04");
    Bt4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            Bt4ActionPerformed(evt);
        }
    });

    btEnviar.setText("Enviar dados");
    btEnviar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btEnviarActionPerformed(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()
                    .addGap(232, 232, 232)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(74, 74, 74)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(187, Short.MAX_VALUE))
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(36, 36, 36)
            .addComponent(btEnviar)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(Bt4)
            .addGap(65, 65, 65))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(51, 51, 51)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(Bt4)
                .addComponent(btEnviar))
            .addGap(61, 61, 61))
    );

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

private void Bt4ActionPerformed(java.awt.event.ActionEvent evt) {                                    
   
}                                   

private void btEnviarActionPerformed(java.awt.event.ActionEvent evt) {                                         
    linha = tabela_consulta.getSelectedRow();
    retorno = String.valueOf(tabela_consulta.getValueAt(linha, 0));
    
    System.out.println("retorno = "+retorno);
   
    dispose();
}                                        

// Variables declaration - do not modify                     
private javax.swing.JButton Bt4;
private javax.swing.JButton btEnviar;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tabela_consulta;
// End of variables declaration                   

public String getRetorno(){
    return retorno;
}

}

Observer

package obs;

/**
*

  • @author User
    */
    public interface Observer {
    public void update(String texto);
    }

Subject

package obs;

/**
*

  • @author User
    
    */
    
    public interface Subject {
    
    public void registerObserver(Observer observer);
    

    public void removeObserver(Observer observer);

    public void notifyAllObservers();
    }

Criado 17 de janeiro de 2020
Ultima resposta 28 de jan. de 2020
Respostas 10
Participantes 3