Chamando outros JFrames

12 respostas
J

Saudações a todos,

Vou tentar ser direto

Tenho dois JFrames

Um chamado Main e outro chamado Sobre

No JFrame Main tenho um botão, que quando clico, ele abre o JFrame Sobre.

Estou fazendo isso usando a seguinte linha

Sobre novoFrame = new Sobre();
novoFrame.setVisible(true);

Quando faço isso, ele abre o JFrame SOBRE.

Só que, ainda assim, o JFrame MAIN fica acessível, podendo abrir quantos JFrames SOBRE for solicitado.

Eu queria saber como faço para chamar um JFrame SOBRE, e na mesma hora, deixar o JFrame MAIN inativo, ate que o JFrame SOBRE seja fechado de qualquer forma.

Grato

Joseph S. Alcântara
Sobral-CE

12 Respostas

D

Ola,

vou dar um exemplo, na sua classe Main coloque algo do tipo :

esse eh o listener do botao Sobre que esta na classe Main.

private void jButtonSobreActionPerformed(java.awt.event.ActionEvent evt) {                                            
        SobreGUI sobreGui = new SobreGUI();
        DesktopPane.add(sobreGui);
        sobreGui.registra(this);
        sobreGui.setVisible(true);
        desabilitaBotao();
    }

coloque esse codigo tambem na classe Main para habilitar/desabilitar o que quiser : (no caso o botao Sobre)

public void desabilitaBotao() {
        jButtonSobre.setEnabled(false);
    }

    public void habilitaBotao() {
        jButtonSobre.setEnabled(true);
    }

E na Classe Sobre coloque algo do tipo :

protected Main mainRetorno;

    public void registra(Main instancia_Atual) {
        mainRetorno = instancia_Atual;
    }

    //use isso para que quando for fechar o Jframe Sobre , seja habilitado o botao Sobre da tela Principal novamente  
    protected void sair() {
        dispose();
        mainRetorno.habilitaBotao();
    }

Como disse eh apenas um exemplo , mas disso eh oque voce precisa para tomar como base e implementar no seu projeto.

espero que ajude, :slight_smile:

flw.

R

Para que o JFrame principal fique inacessível enquando você usa a janela Sobre, implemente a janela Sobre como um JDialog modal e não como um JFrame.

J

Um exemplo do que eu quero pode ser visto no OpenOffice

Quando abre a janela

Tools > Options
Ferramentas > Opções

Observe que quando a janela OPÇÕES é aberta, a janela que fica atrás, fica inativa. E eu só continuo a editar alguma coisa se essa janela OPÇÕES fechar. Acho que não é o caso do enable, pois ele só voltaria se eu apertasse no botao correto.

vlw

M

Olá

Como roger disse use JDialog modal ao invés de JFrame.

Fui…

R

Exemplo de código:

import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class FrameGuj extends JFrame {
  public FrameGuj() {
    setTitle("Teste de diálogo modal");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    getContentPane().setLayout(new BorderLayout());

    JPanel painel = new JPanel();
    painel.setLayout(new BorderLayout());
    getContentPane().add(painel, BorderLayout.CENTER);

    JButton botao = new JButton("Abrir Diálogo Sobre...");
    botao.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        new DialogoModal(FrameGuj.this, "Diálogo Sobre", true)
          .setVisible(true);
      }
    });
    painel.add(botao, BorderLayout.CENTER);

    setSize(500, 300);
    setLocationRelativeTo(null);
  }

  public static void main(String[] args) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        new FrameGuj().setVisible(true);
      }
    });
  }
}

class DialogoModal extends JDialog {
  public DialogoModal(Frame owner, String title, boolean modal) {
    super(owner, title, modal);

    getContentPane().setLayout(new BorderLayout());

    JPanel painel = new JPanel();
    painel.setLayout(new BorderLayout());
    getContentPane().add(painel, BorderLayout.CENTER);

    JLabel label = new JLabel("Este JDialog é modal");
    painel.add(label, BorderLayout.CENTER);

    setSize(300, 200);
    setLocationRelativeTo(null);
 }
}
J

Qual a diferença entre um JDialog e um JFrame?

É que na faculdade o professor só passou o JFrame, será que não dá pra fazer com JFrame?

vlw

Seguem as classes

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

/*
 * Sobre.java
 *
 * Created on 23/06/2009, 23:08:19
 */

package mansystem;

/**
 *
 * @author Joseph
 */
public class Sobre extends javax.swing.JFrame {

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

        fechar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        texto = new javax.swing.JTextPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Sobre ManSystem");
        setAlwaysOnTop(true);
        setResizable(false);

        fechar.setText("Fechar");
        fechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fecharActionPerformed(evt);
            }
        });
        getContentPane().add(fechar, java.awt.BorderLayout.SOUTH);

        texto.setEditable(false);
        texto.setText("Programa desenvolvido por\nJoseph Soares Alcântara");
        texto.setOpaque(false);
        jScrollPane1.setViewportView(texto);

        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-220)/2, (screenSize.height-120)/2, 220, 120);
    }// </editor-fold>

    private void fecharActionPerformed(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 Sobre().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton fechar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane texto;
    // End of variables declaration

}


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

/*
 * Main.java
 *
 * Created on 21/06/2009, 07:40:33
 */

package mansystem;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;

/**
 *
 * @author Joseph
 */
public class Main extends javax.swing.JFrame {

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

        jMenuBar1 = new javax.swing.JMenuBar();
        arquivo = new javax.swing.JMenu();
        sair = new javax.swing.JMenuItem();
        editar = new javax.swing.JMenu();
        calc = new javax.swing.JMenuItem();
        notepad = new javax.swing.JMenuItem();
        ajuda = new javax.swing.JMenu();
        conteudo = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        sobre = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        arquivo.setText("Arquivo");

        sair.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0));
        sair.setText("Sair");
        sair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sairActionPerformed(evt);
            }
        });
        arquivo.add(sair);

        jMenuBar1.add(arquivo);

        editar.setText("Editar");

        calc.setText("Calculadora");
        calc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                calcActionPerformed(evt);
            }
        });
        editar.add(calc);

        notepad.setText("Editor de Texto");
        notepad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                notepadActionPerformed(evt);
            }
        });
        editar.add(notepad);

        jMenuBar1.add(editar);

        ajuda.setText("Ajuda");

        conteudo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
        conteudo.setText("Conteúdo da ajuda");
        ajuda.add(conteudo);
        ajuda.add(jSeparator1);

        sobre.setText("Sobre");
        sobre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sobreActionPerformed(evt);
            }
        });
        ajuda.add(sobre);

        jMenuBar1.add(ajuda);

        setJMenuBar(jMenuBar1);

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

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-600)/2, (screenSize.height-400)/2, 600, 400);
    }// </editor-fold>                        

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

    private void calcActionPerformed(java.awt.event.ActionEvent evt) {                                     
        try {
            Runtime.getRuntime().exec("calc");
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                    

    private void notepadActionPerformed(java.awt.event.ActionEvent evt) {                                        
        try {
            Runtime.getRuntime().exec("notepad");
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
}                                       

    private void sobreActionPerformed(java.awt.event.ActionEvent evt) {                                      
        Sobre newFrame = new Sobre();
        newFrame.setVisible(true);
    }                                     

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

    // Variables declaration - do not modify                     
    private javax.swing.JMenu ajuda;
    private javax.swing.JMenu arquivo;
    private javax.swing.JMenuItem calc;
    private javax.swing.JMenuItem conteudo;
    private javax.swing.JMenu editar;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JMenuItem notepad;
    private javax.swing.JMenuItem sair;
    private javax.swing.JMenuItem sobre;
    // End of variables declaration                   

}

Execute a classe Main no NetBeans

Depois vá em ajuda > sobre

Tentei o código ai do colega acima mas estava dando erro e eu não soube resolver

R

Até onde sei, JFrame’s não podem se comportar como janelas modais, então a saída é realmente usar JDialog. Segue em anexo o exemplo que citei na mensagem anterior, empacotado como projeto do NetBeans 6.7 RC3.

J

Consegui o que queria.
Grato a todos.

Ai vai um arquivo que to tentando desenrolar… Tá ficando horrível. Mas é de natureza minha.

Falow a todos!

L

se conseguiu me da um help entao tenho a mesma duvida :smiley: so qro deixar a tela principal inativa qnd chamar outras por cima :slight_smile:

R

Tem alguma propriedade no netbeans que possa ser modificado para essa finalidade?

J

Eu utilizei o que o amigo comentou logo acima. Usei uma janela JDialog modal.

S

Olá Jose,
É possível sim utilizar dois frames para exibir o conteúdo do segundo e deixar o primeiro desabilitado no fundo. Vou recomendar a você a execução do código DialogDemo disponível na página de exemplos do java. Você pode acessar pelo link abaixo:

Se quiser baixar o código de exemplo para estudo use o link abaixo:

E se quiser conhecer a página que contém vários exemplos de uso dos componentes SWING pode ir para a página:

Tem muita coisa boa por lá.

Sérgio

Criado 23 de junho de 2009
Ultima resposta 27 de jun. de 2011
Respostas 12
Participantes 7