Como adicionar um JInternalFrame em um JDesktopPane? [RESOLVIDO]

5 respostas
Cavalo_de_Troia

Galera sou iníciante, porém antes de postar dei uma pesquisada, encontrei algumas dicas mas nada que me ajudasse concretamente.
É o seguinte, estou utilizando o netbeans para efetuar um trabalho de faculdade, criei um JFrame e adicionei um JDesktopPane, coloquei os menus e submenus, essa é minha tela principal (MDI), depois criei um outro formulário, chamado telaCliente que extends um JInternalFrame, nesse formulário adicionei todos os componentes de uma tela básica de cadastro de cliente.
Bom… a minha dificuldade é abrir essa telaCliente dentro do JDesktopPane, nos exemplo que achei na pesquisa, todos mostram algo parecido com isso:

JInternalFrame mdiFilha1 = new JInternalFrame("Cliente", true, true, true, true);  
       mdiFilha1.setBounds(110, 10, 800, 700);                
       desktopPaneTelaPrincipal.add(mdiFilha1);                
       mdiFilha1.setVisible(true);

Obs.: quero chamar a telaCliente acionando uma das opções do Menu.

Espero que alguém possa me dar uma força!

Desde já agradeço!

5 Respostas

criador

Se entendi bem o que você quer, segue um exemplo abaixo.

Bom, você precisa dar o new Janela().setVisible(true) na ação do seu menú.

Exemplo:

JMenuBar menu_principal = new JMenuBar();
JMenu menu_cliente = new JMenu("Cliente");
JMenuItem[1] menu_cliente_item = new JMenuItem[1];

menu_principal.add(menu_cliente);

menu_cliente_item[0] = new JMenuItem(acao);
menu_cliente_item[0].setText("Cadastrar");

menu_cliente.add(menu_cliente_item[0]);

Aqui você criou o menú principal que conterá o submenu Cliente que conterá o submenu Cadastrar.

Porém, para chamar a sua aplicação, note que foi colocado uma ação no new JMenuItem(acao).

É nesta ação que você dará o new na sua classe.

Action acao = new AbstractAction() {
     public void actionPerformed(ActionEvent ae) {
          new Janela().setVisible(true);
     }
};

Acredito que com isto seu problema seja resolvido.

Abraço!

Cavalo_de_Troia

Amigo, obrigado por responder, entretanto, minha diculdade não é em criar o menu ou submenu, a minha dificuldade é carregar o JInternalFrame na minha tela principal que é um MDI, ou seja, FRAME + JDESKTOPPANE.
Por exemplo estava instanciando a classe telaCliente, porém por se tratar de um JInternalFrame, a tela não abre.
Queria saber a forma correta de carregar uma tela JInternalFrame em um JdesktopPane. Abç

S

Olá amigo

veja este exemplo de uma tela principal:

package comap;

import java.beans.PropertyChangeListener;
import java.sql.SQLException;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.AbstractAction;
import javax.swing.JFrame;


public class FramePrincipal extends JFrame implements ActionListener{

    private MDIDesktopPane desktop = new MDIDesktopPane();
//    private JMenuBar menuBar = new JMenuBar();
    private JMenu fileMenu = new JMenu("File");
    private JMenuItem newMenu = new JMenuItem("New");
    private JScrollPane scrollPane = new JScrollPane();
    public JToolBar toolBar;
    private AbstractAction actionNew;
    private AbstractAction actionOpen;
    private AbstractAction actionSave;
    private AbstractAction actionExit;
    private AbstractAction actionPatrimonio;
    private AbstractAction actionBaixas;
    public int getHeight;
    public Boolean telaClientes = false;
    public int larguraBotao = 100;
    public int alturaBotao = 50;
    public static final String FontNames[] = {"Serif", "SansSerif", "Courier"};
    protected Font fonts[];
    protected JMenuItem[] fontMenus;
    protected JCheckBoxMenuItem boldMenu = new JCheckBoxMenuItem("Bold");
    protected JCheckBoxMenuItem italicMenu = new JCheckBoxMenuItem("Italic");
    static ImageIcon sairButtonIcon = createImageIcon("resources/exit24.png");
    ImageIcon patrimonioButtonIcon = createImageIcon("resources/kontact_contacts.png");
    ImageIcon baixasButtonIcon = createImageIcon("resources/systemsettings.png");
    ImageIcon sobreButtonIcon = createImageIcon("resources/stockhelp.png");
    static FramePatrimonio framePatrimonio;
    static FrameBaixas frameBaixas;
    public JLabel LabelDataHora;
    public JLabel LabelUsuario;
    static JMenuBar menu;
    public JMenuBar menuBar;

    public Connection dbConnection = null;

    public FramePrincipal() throws ClassNotFoundException, SQLException {
//        menuBar.add(fileMenu);
        super("Comap - Sistema da Comap V. 1.0");

        this.dbConnection = bd.ConexaoBancoDados.getInstance().conexao();

        javax.swing.UIManager.put("OptionPane.yesButtonText", "Sim");
        javax.swing.UIManager.put("OptionPane.noButtonText", "Não");
        javax.swing.UIManager.put("OptionPane.okButtonText", "Ok");
        javax.swing.UIManager.put("OptionPane.cancelButtonText", "Cancelar");

        fonts = new Font[FontNames.length];
        for (int i = 0; i < FontNames.length; i++) {
            fonts[i] = new Font(FontNames[i], Font.PLAIN, 12);
        }

        int inset = 50;
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        getHeight = screenSize.height;
        setBounds(inset, inset,
                screenSize.width - inset * 2,
                screenSize.height - inset * 2);
        menuBar = createMenuBar();
        menuBar.add(new WindowMenu(desktop));
//        fileMenu.add(newMenu);
        setJMenuBar(menuBar);
        //setTitle("MDI Test");
        scrollPane.getViewport().add(desktop);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        getContentPane().add(toolBar, BorderLayout.NORTH);


        JLabel LabelUsuario = new JLabel();
        JLabel LabelDataHora = new JLabel();

        LabelUsuario.setText("Usuário:                Data: ");
        LabelUsuario.setBounds(110, 01, 10, 30);
        LabelDataHora.setText("Data: ");
        LabelDataHora.setBounds(200, 01, 280, 30);

        StatusBar statusBar = new StatusBar();
        statusBar.add(LabelUsuario);
        getContentPane().add(statusBar, BorderLayout.SOUTH);


        getContentPane().add(desktop);

        addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                quit();
            }
        });
        newMenu.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                desktop.add(new TextFrame());
            }
        });
        desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        FramePrincipal.setDefaultLookAndFeelDecorated(true);
        LookAndFeelInfo[] lafs = (LookAndFeelInfo[]) UIManager.getInstalledLookAndFeels();

        desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);

        this.setVisible(true);
        this.implementarTeclado();
        this.setExtendedState(MAXIMIZED_BOTH);     
    }

    public static void main(String[] args) throws InterruptedException, ClassNotFoundException, SQLException {
        createAndShowGUI();

    }

    public static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = FrameModelo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

    protected JMenuBar createMenuBar() {
        final JMenuBar menuBar = new JMenuBar();

        JMenu assistencia = new JMenu("Patrimônio");
        assistencia.setMnemonic('P');

        //ImageIcon iconNew = new ImageIcon(clienteButtonIcon);

//        JMenu menu = new JMenu("Assistência");
//        menu.setMnemonic(KeyEvent.VK_A);
//        menu.setMnemonic('A');

        actionPatrimonio = new AbstractAction("Patrimonio ", patrimonioButtonIcon) {

            public void actionPerformed(ActionEvent e) {
                acaoBotoes(e);
            }
        };

//        JMenuItem item = assistencia.add(actionClientes);
        JMenuItem item = new JMenuItem("Patrimônio");
        item.setMnemonic(KeyEvent.VK_A);
        item.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_A, ActionEvent.ALT_MASK));
        item.setActionCommand("patrimonio");
        item.setIcon(patrimonioButtonIcon);
        item.addActionListener(this);
        assistencia.add(item);

//        JMenuItem item = assistencia.add(actionClientes);

        actionBaixas = new AbstractAction("Baixas ", baixasButtonIcon) {

            public void actionPerformed(ActionEvent e) {
                acaoBotoes(e);
            }
        };

        item = new JMenuItem("Baixas");
        item.setMnemonic(KeyEvent.VK_A);
        item.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_A, ActionEvent.ALT_MASK));
        item.setActionCommand("baixas");
        item.setIcon(patrimonioButtonIcon);
        item.addActionListener(this);
        assistencia.add(item);


        assistencia.addSeparator();

        actionExit = new AbstractAction("Sair", sairButtonIcon) {

            public void actionPerformed(ActionEvent e) {
                acaoBotoes(e);
            }
        };

//        item = assistencia.add(actionExit);
        item = new JMenuItem("Sair");
        item.setMnemonic(KeyEvent.VK_F4);
        item.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_F4, ActionEvent.ALT_MASK));
        item.setActionCommand("sair");
        item.setIcon(sairButtonIcon);
        item.addActionListener(this);

        item.setMnemonic('S');
        assistencia.add(item);

        menuBar.add(assistencia);

        toolBar = new JToolBar();

        JButton btn1 = toolBar.add(actionPatrimonio);
        btn1.setToolTipText("Cadastro de Patrimônio");
        btn1.setActionCommand("patrimonio");
        btn1.setIcon(patrimonioButtonIcon);
        btn1.setText("F2-Patrimônio");
        btn1.setPreferredSize(new Dimension(50, 50));
        btn1.setMaximumSize(new Dimension(larguraBotao, alturaBotao));

        JButton btn2 = toolBar.add(actionBaixas);
        btn2.setToolTipText("Baixas");
        btn2.setIcon(baixasButtonIcon);
        btn2.setActionCommand("baixas");
        btn2.setText("F3-Baixas   ");
        btn2.setPreferredSize(new Dimension(50, 50));
        btn2.setMaximumSize(new Dimension(larguraBotao, alturaBotao));
//
//        JButton btn3 = toolBar.add(actionMarcas);
//        btn3.setToolTipText("Cadastro de Marcas");
//        btn3.setIcon(ordemservicoButtonIcon);
//        btn3.setActionCommand("marcas");
//        btn3.setText("F4-Marcas  ");
//        btn3.setPreferredSize(new Dimension(50, 50));
//        btn3.setMaximumSize(new Dimension(larguraBotao, alturaBotao));

        getContentPane().add(toolBar, BorderLayout.NORTH);


        ActionListener fontListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                //    updateMonitor();
            }
        };

        JMenu mFont = new JMenu("Font");
        mFont.setMnemonic('o');

        ButtonGroup group = new ButtonGroup();
        fontMenus = new JMenuItem[FontNames.length];
        for (int k = 0; k < FontNames.length; k++) {
            int m = k + 1;
            fontMenus[k] = new JRadioButtonMenuItem(m + " " + FontNames[k]);
            boolean selected = (k == 0);
            fontMenus[k].setSelected(selected);
            fontMenus[k].setMnemonic('1' + k);
            fontMenus[k].setFont(fonts[k]);
            fontMenus[k].addActionListener(fontListener);
            group.add(fontMenus[k]);
            mFont.add(fontMenus[k]);
        }

        mFont.addSeparator();

        boldMenu.setMnemonic('b');
        Font fn = fonts[1].deriveFont(Font.BOLD);
        boldMenu.setFont(fn);
        boldMenu.setSelected(false);
        boldMenu.addActionListener(fontListener);
        mFont.add(boldMenu);

        italicMenu.setMnemonic('i');
        fn = fonts[1].deriveFont(Font.ITALIC);
        italicMenu.setFont(fn);
        italicMenu.setSelected(false);
        italicMenu.addActionListener(fontListener);
        mFont.add(italicMenu);

        menuBar.add(mFont);

        getContentPane().add(toolBar, BorderLayout.NORTH);

        return menuBar;
    }


    public void acaoBotoes(ActionEvent e) {
        if ("patrimonio".equals(e.getActionCommand())) { //new
            try {
                //new
                createFramePatrimonio();
            } catch (Exception ex) {
                Logger.getLogger(FramePrincipal.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        if ("baixas".equals(e.getActionCommand())) { //new
            try {
                //new
                createFrameBaixas();
            } catch (Exception ex) {
                Logger.getLogger(FramePrincipal.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        if ("sair".equals(e.getActionCommand())) { //new
            int i = JOptionPane.showOptionDialog(null, "Tem certeza que deseja sair?", "Sair do Sistema", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, JOptionPane.NO_OPTION);
            if (i == JOptionPane.YES_OPTION) {
                quit();
            }
        }

    }

    protected void createFramePatrimonio() throws PropertyVetoException, Exception {
        menu = menuBar;
        if (framePatrimonio == null) {
            framePatrimonio = new FramePatrimonio(this.dbConnection);
            framePatrimonio.setVisible(true); //necessary as of 1.3
            desktop.add(framePatrimonio);
            framePatrimonio.pack();
            desktop.getDesktopManager().maximizeFrame(framePatrimonio);
        } else {
            framePatrimonio.setVisible(true);
        }
        try {
            framePatrimonio.setSelected(true);
        } catch (java.beans.PropertyVetoException e) {
        }
        
    }

     protected void createFrameBaixas() throws PropertyVetoException, Exception {
        menu = menuBar;
        if (frameBaixas == null) {
            frameBaixas = new FrameBaixas(this.dbConnection);
            frameBaixas.setVisible(true); //necessary as of 1.3
            desktop.add(frameBaixas);
            frameBaixas.pack();
            desktop.getDesktopManager().maximizeFrame(frameBaixas);
        } else {
            frameBaixas.setVisible(true);
        }
        try {
            frameBaixas.setSelected(true);
        } catch (java.beans.PropertyVetoException e) {
        }
        
    }



    protected void quit() {
        int i = JOptionPane.showOptionDialog(null, "Tem certeza que deseja sair?", "Sair do Sistema", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, JOptionPane.NO_OPTION);
        if (i == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }

    private static void createAndShowGUI() throws InterruptedException, ClassNotFoundException, SQLException {
        //Make sure we have nice window decorations.

        JFrame.setDefaultLookAndFeelDecorated(true);

        //Create and set up the window.
        FramePrincipal frameprincipal = new FramePrincipal();
        frameprincipal.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

        //Display the window.
        frameprincipal.setVisible(true);
        frameprincipal.setExtendedState(MAXIMIZED_BOTH);
    }

    public void implementarTeclado() {

        JPanel contentPane = (JPanel)this.getContentPane();
        InputMap inputMap = contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap actionMap = contentPane.getActionMap();
        
        inputMap.put(KeyStroke.getKeyStroke("F1"),"F1String");
        actionMap.put("F1String", new AbstractAction(){

            public void actionPerformed(ActionEvent arg0) {
                F1();
            }
            
        });

        inputMap.put(KeyStroke.getKeyStroke("F2"),"F2String");
        actionMap.put("F2String", new AbstractAction(){

            public void actionPerformed(ActionEvent arg0) {
                try{
                    F2();
                }catch(Exception e){
                    avisaException(e);
                }
            }
        });

        inputMap.put(KeyStroke.getKeyStroke("F3"),"F3String");
        actionMap.put("F3String", new AbstractAction(){

            public void actionPerformed(ActionEvent arg0) {
                try{
                    F3();
                }catch(Exception e){
                    avisaException(e);
                }
            }
        });        
    }

    public void avisaException(Exception e){
        JOptionPane.showMessageDialog(null, e.getMessage());
        this.setVisible(true);
        this.setFocusable(true);;
    }

    public void F1() {
        JOptionPane.showMessageDialog(null, "Olha o PROMPT!");
        this.setVisible(true);
        this.setFocusable(true);;
    }

    public void F2() throws PropertyVetoException, Exception {
        createFramePatrimonio();
    }

    public void F3() throws PropertyVetoException, Exception {
        createFrameBaixas();
    }


    /*public void listenKeyboard(Component[] cs) {
        for (Component c : cs) {
            c.addKeyListener(this);
        }
    }*/

    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_F1) {
            F1();
        }
        if (e.getKeyCode() == KeyEvent.VK_F2) {
            try {
                F2();
            } catch (PropertyVetoException ex) {
                Logger.getLogger(FramePrincipal.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(FramePrincipal.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (e.getKeyCode() == KeyEvent.VK_F3) {
            try {
                F3();
            } catch (PropertyVetoException ex) {
                Logger.getLogger(FramePrincipal.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(FramePrincipal.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void keyReleased(KeyEvent e) {
    }

    public void keyTyped(KeyEvent e) {
    }

    public void actionPerformed(ActionEvent e) {
        if ("patrimonio".equals(e.getActionCommand())) { //new
            acaoBotoes(e);
        }

        if ("baixas".equals(e.getActionCommand())) { //new
            acaoBotoes(e);
        }

        if ("sair".equals(e.getActionCommand())) { //new
           quit();
        }
        
}

}

Silvio Guedes

Marky.Vasconcelos

No seu JFrame principal, invés de adicionar o JDesktopPane a ele faça o seguinte.

frame.setContentPane(new JDesktopPane());
frame.add(new MyInternalFrame());
Cavalo_de_Troia

Galera, resolvi com o seguinte código:

public void actionPerformed(ActionEvent e){
        if(e.getSource() == jMenuItemCliente){                
            TelaCliente telaCliente = new TelaCliente();
            getContentPane().add(telaCliente);
            telaCliente.setVisible(true);

Com isso consegui que o meu JInternalFrame acionado através do JMenuItem fosse carregado dentro do JDeskTopPane.

Obrigado a todos que responderam!

Criado 1 de outubro de 2009
Ultima resposta 8 de out. de 2009
Respostas 5
Participantes 4