JDesktopPane Imagem de fundo - Não estou entendendo

9 respostas
S

Gente , pesquisei mas não entendi!
Li nesse tópico, http://www.guj.com.br/java/131490-background-no-jdesktoppane

O colega didiosam passou esse código :
package a;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JDesktopPane;

/**
 *
 * 
 */

public class BackGround extends JDesktopPane {  
  
        private Image img;  
  
        public BackGround() {  
            try {  
                img = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("/HERSCHEL.JPG"), "HERSCHEL.JPG"));  
            } catch (Exception ex) {  
            }  
        }  
  
        @Override  
        public void paintComponent(Graphics g) {  
            super.paintComponent(g);  
            if (img != null) {  
                Dimension dimension = this.getSize();  
                int x = (int)(dimension.getWidth() - img.getWidth(this)) / 2;  
                int y = (int)(dimension.getHeight() - img.getHeight(this)) / 2;  
  
                g.drawImage(img, x, y, img.getWidth(this), img.getHeight(this), this);  
            } else {  
                g.drawString("Imagem nao encontrada", 50, 50);  
            }  
        }  
    }

naturalmente, criei uma classe separada somente para isso! Mas como que eu faço meu jDesktopPane chamar esse método para mudar o fundo ? Tipo, meu jDesktopPane ta numa classe Jframe, e a classe BackGround esta em outro lugar!

mais uma dúvida, posso usar a palavra BackGround ou ela ja é usada pelo Java?

9 Respostas

V

Ele chama sozinho.

Esse BackGround é um JDesktopPane. Então, no seu JFrame, troque a criação do DesktopPane para:

S
no protocol: HERSCHEL.JPG no protocol: HERSCHEL.JPG [Ljava.lang.StackTraceElement;@52b57e9a
Então a minha classe background esá assim :
package cooling;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JDesktopPane;
import javax.swing.JOptionPane;

/**
 *
 * 
 */

public class BackGround extends JDesktopPane {  
  
        private Image img;  
  
        public BackGround() {  
            try {  
                img = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("/HERSCHEL.JPG"), "HERSCHEL.JPG"));  
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
                System.out.println("" + ex.getMessage());
                 System.out.println("" + ex.getLocalizedMessage());
                    System.out.println(" " + ex.getStackTrace());
            }  
            
        }  
  
        @Override  
        public void paintComponent(Graphics g) {  
            super.paintComponent(g);  
            if (img != null) {  
                Dimension dimension = this.getSize();  
                int x = (int)(dimension.getWidth() - img.getWidth(this)) / 2;  
                int y = (int)(dimension.getHeight() - img.getHeight(this)) / 2;  
  
                g.drawImage(img, x, y, img.getWidth(this), img.getHeight(this), this);  
            } else {  
                g.drawString("Imagem nao encontrada", 50, 50);  
            }  
        }  
    }

Tenho um arquivo chamado HERSCHEL.JPG dentro do package, junto com as outras classes do projeto!

O que estou fazendo errado?

V

Faça a carga assim:

S

input == null!
input == null!
[Ljava.lang.StackTraceElement;@4b7f1841

V

Coloque sua imagem na mesma pasta dos fontes, inclusive o mesmo pacote. Por exemplo, se o pacote for br.com.guj vc deverá abrir com:

É importante verificar se as letras maiúsculas/minúsculas batem.

S

Assim o erro parou!
img = javax.imageio.ImageIO.read(getClass().getResourceAsStream("HERSCHEL.jpg"));

mas agora é o seguinte, quando eu tento clicar no botao multiplayer pra ele abrir uma jinternalframe, ele da esse erro:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: illegal component position at java.awt.Container.addImpl(Container.java:1048) at javax.swing.JLayeredPane.addImpl(JLayeredPane.java:212) at javax.swing.JDesktopPane.addImpl(JDesktopPane.java:470) at java.awt.Container.add(Container.java:365) at cooling.Main.jButton_MultiPlayerActionPerformed(Main.java:174) at cooling.Main.access$100(Main.java:24) at cooling.Main$2.actionPerformed(Main.java:110) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236) at java.awt.Component.processMouseEvent(Component.java:6288) at javax.swing.JComponent.processMouseEvent(JComponent.java:3267) at java.awt.Component.processEvent(Component.java:6053) at java.awt.Container.processEvent(Container.java:2041) at java.awt.Component.dispatchEventImpl(Component.java:4651) at java.awt.Container.dispatchEventImpl(Container.java:2099) at java.awt.Component.dispatchEvent(Component.java:4481) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168) at java.awt.Container.dispatchEventImpl(Container.java:2085) at java.awt.Window.dispatchEventImpl(Window.java:2478) at java.awt.Component.dispatchEvent(Component.java:4481) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:643) at java.awt.EventQueue.access$000(EventQueue.java:84) at java.awt.EventQueue$1.run(EventQueue.java:602) at java.awt.EventQueue$1.run(EventQueue.java:600) at java.security.AccessController.doPrivileged(Native Method) at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87) at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98) at java.awt.EventQueue$2.run(EventQueue.java:616) at java.awt.EventQueue$2.run(EventQueue.java:614) at java.security.AccessController.doPrivileged(Native Method) at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87) at java.awt.EventQueue.dispatchEvent(EventQueue.java:613) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) CONSTRUÍDO COM SUCESSO (tempo total: 9 segundos)
/*
 * Main.java
 *
 * Created on 21/01/2012, 16:51:09
 */
package cooling;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.beans.PropertyVetoException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Locale;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;


/**
 *
 * @author André Vinícius Lopes
 */
public class Main extends javax.swing.JFrame {
    

    /** Creates new form Main */
    public Main() {
       
        initComponents();
        jDesktopPane_Main = new BackGround();
        
    }

    /** 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() {

        jInternalFrame_Multiplayer = new javax.swing.JInternalFrame();
        jDesktopPane_MP = new javax.swing.JDesktopPane();
        jButton_CharImage = new javax.swing.JButton();
        jTextField_NameChar = new javax.swing.JTextField();
        jButton_Attack = new javax.swing.JButton();
        jTextField_CharInfo = new javax.swing.JTextField();
        jDesktopPane_Main = new javax.swing.JDesktopPane();
        jLabel1 = new javax.swing.JLabel();
        jButton_MultiPlayer = new javax.swing.JButton();
        jButton_Readme = new javax.swing.JButton();
        jButton_Sair = new javax.swing.JButton();
        jLabel_Copyrighted = new javax.swing.JLabel();
        jButton_Settings = new javax.swing.JButton();
        jTextField_TimeDate = new javax.swing.JTextField();
        jMenuBar_Main = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();

        jInternalFrame_Multiplayer.setVisible(true);

        jButton_CharImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cooling/SpriteSoldier.jpg"))); // NOI18N
        jButton_CharImage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_CharImageActionPerformed(evt);
            }
        });
        jButton_CharImage.setBounds(20, 90, 90, 90);
        jDesktopPane_MP.add(jButton_CharImage, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jTextField_NameChar.setBackground(new java.awt.Color(255, 255, 51));
        jTextField_NameChar.setEditable(false);
        jTextField_NameChar.setText("Name  of your Character");
        jTextField_NameChar.setBounds(20, 40, 190, 30);
        jDesktopPane_MP.add(jTextField_NameChar, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton_Attack.setText("Attack");
        jButton_Attack.setBounds(240, 100, 73, 23);
        jDesktopPane_MP.add(jButton_Attack, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jTextField_CharInfo.setBackground(new java.awt.Color(0, 204, 204));
        jTextField_CharInfo.setText("Character Information");
        jTextField_CharInfo.setBounds(20, 200, 160, 150);
        jDesktopPane_MP.add(jTextField_CharInfo, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout jInternalFrame_MultiplayerLayout = new javax.swing.GroupLayout(jInternalFrame_Multiplayer.getContentPane());
        jInternalFrame_Multiplayer.getContentPane().setLayout(jInternalFrame_MultiplayerLayout);
        jInternalFrame_MultiplayerLayout.setHorizontalGroup(
            jInternalFrame_MultiplayerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jDesktopPane_MP, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 508, Short.MAX_VALUE)
        );
        jInternalFrame_MultiplayerLayout.setVerticalGroup(
            jInternalFrame_MultiplayerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jDesktopPane_MP, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 348, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Rod", 3, 18));
        jLabel1.setText("Cooling Project");
        jLabel1.setBounds(10, 20, 250, 30);
        jDesktopPane_Main.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton_MultiPlayer.setText("Multiplayer");
        jButton_MultiPlayer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_MultiPlayerActionPerformed(evt);
            }
        });
        jButton_MultiPlayer.setBounds(10, 250, 90, 23);
        jDesktopPane_Main.add(jButton_MultiPlayer, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton_Readme.setText("Leia-Me");
        jButton_Readme.setBounds(110, 250, 80, 23);
        jDesktopPane_Main.add(jButton_Readme, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton_Sair.setText("Sair");
        jButton_Sair.setBounds(200, 250, 51, 23);
        jDesktopPane_Main.add(jButton_Sair, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel_Copyrighted.setText("Cooling Project - All rights Reserved   2012-2014");
        jLabel_Copyrighted.setBounds(230, 320, 220, 14);
        jDesktopPane_Main.add(jLabel_Copyrighted, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton_Settings.setText("Configurações");
        jButton_Settings.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_SettingsActionPerformed(evt);
            }
        });
        jButton_Settings.setBounds(323, 10, 120, 23);
        jDesktopPane_Main.add(jButton_Settings, javax.swing.JLayeredPane.DEFAULT_LAYER);
        jTextField_TimeDate.setBounds(10, 310, 170, 20);
        jDesktopPane_Main.add(jTextField_TimeDate, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jMenu1.setText("Arquivo");
        jMenuBar_Main.add(jMenu1);

        jMenu2.setText("Opções");
        jMenuBar_Main.add(jMenu2);

        jMenu3.setText("Outros");
        jMenuBar_Main.add(jMenu3);

        setJMenuBar(jMenuBar_Main);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jDesktopPane_Main, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jDesktopPane_Main, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE)
        );

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

private void jButton_MultiPlayerActionPerformed(java.awt.event.ActionEvent evt) {                                                    

    
    JInternalFrame internalFrame = new JInternalFrame();
     
      internalFrame = jInternalFrame_Multiplayer;
      internalFrame.setClosable(true);//Se o frame vai poder ser fechado pelo botão fechar   
      internalFrame.setIconifiable(true);//Se o frame vai poder ser minimizado.  
      internalFrame.setResizable(true);//Pemite editar o tamanho.
      internalFrame.setVisible(true);  
      jDesktopPane_Main.add(internalFrame);
      
      
        try {
            //Torna o seu painel interno visível  
            internalFrame.setMaximum(true);
        } catch (PropertyVetoException ex) {
            JOptionPane.showMessageDialog(null,ex.getMessage());
             JOptionPane.showMessageDialog(null,ex.getStackTrace());
        }
        
     
      internalFrame.setVisible(true);  
}                                                   

private void jButton_SettingsActionPerformed(java.awt.event.ActionEvent evt) {                                                 
// TODO add your handling code here:
}                                                

private void jButton_CharImageActionPerformed(java.awt.event.ActionEvent evt) {                                                  
// TODO add your handling code here:
}                                                 

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton_Attack;
    private javax.swing.JButton jButton_CharImage;
    private javax.swing.JButton jButton_MultiPlayer;
    private javax.swing.JButton jButton_Readme;
    private javax.swing.JButton jButton_Sair;
    private javax.swing.JButton jButton_Settings;
    private javax.swing.JDesktopPane jDesktopPane_MP;
    private javax.swing.JDesktopPane jDesktopPane_Main;
    private javax.swing.JInternalFrame jInternalFrame_Multiplayer;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel_Copyrighted;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar_Main;
    private javax.swing.JTextField jTextField_CharInfo;
    private javax.swing.JTextField jTextField_NameChar;
    public static javax.swing.JTextField jTextField_TimeDate;
    // End of variables declaration                   

    //Métodos Construídos
    
    public static void TimeDateDisplay()
    {
        
    }
    
    
    
}

Se eu tirar o jDesktopPane_Main = new BackGround(); , ele funciona normalmente

E mais, ele nao mudou o background... continua aquele padrao azul do java

V

Você deveria ter mudado isso dentro do initComponents. Eu não uso Netbeans, não sei como te auxiliar a fazer isso pela IDE.

J

Pessoal peguei um código (segue o link http://javafree.uol.com.br/viewtopic.jbb?t=865627) que colocar uma imagem de fundo no JDesktopPane, segue ai:

import java.awt.Graphics;  
import java.awt.Image;  
import java.awt.Toolkit;  
import javax.swing.JDesktopPane;  
  
public class JDesktopPaneComImage extends JDesktopPane {  
  
   private static final long serialVersionUID = 1L;  
   Image imagem;  
  
   public JDesktopPaneComImage(String caminho) {  
      imagem = Toolkit.getDefaultToolkit().getImage(getClass().getResource(caminho));
   }  
  
    @Override
   public void paintComponent(Graphics g) {  
      super.paintComponent(g);  
      if(imagem != null)   {  
         g.drawImage(imagem, 0, 0, this.getWidth(), this.getHeight(), this);   
      }  
   }  
}

E testando com esse código funciona legal:

public class Teste{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        JFrame teste = new JFrame();
        JDesktopPane d = new JDesktopPaneComImage("desktopSisGEAC.jpg");
        teste.setSize(400, 400);
        teste.setExtendedState(JFrame.MAXIMIZED_BOTH);
        teste.add(d);
        teste.setVisible(true);
    }

Sendo que eu tenho uma classe que extende javax.swing.JFrame e coloco o código que substitui a imagem no construtor, simplesmente não funciona, segue o código:

import javax.swing.JDesktopPane;
import javax.swing.JFrame;

/**
 *
 * @author JUNIOR
 */
public class GUIPrincipal extends javax.swing.JFrame {

    /**
     * Creates new form GUIPrincipal
     */
    
    public GUIPrincipal(){
        initComponents();
        
        this.desktop = new JDesktopPaneComImage("desktopSisGEAC.jpg");
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.setLocationRelativeTo(null);
        this.add(this.desktop);
    }

    /**
     * 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() {

        desktopPane = new javax.swing.JDesktopPane();
        menuBar = new javax.swing.JMenuBar();
        menuArquivo = new javax.swing.JMenu();
        itemDeMenuImportaBase = new javax.swing.JMenuItem();
        itemDeMenuExportaBase = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        itemDeMenuSair = new javax.swing.JMenuItem();
        menuCadastro = new javax.swing.JMenu();
        itemDeMenuExame = new javax.swing.JMenuItem();
        itemDeMenuCadPaciente = new javax.swing.JMenuItem();
        itemDeMenuCadProfissional = new javax.swing.JMenuItem();
        itemDeMenuCadUsuario = new javax.swing.JMenuItem();
        menuRelatorio = new javax.swing.JMenu();
        itemDeMenuGeral = new javax.swing.JMenuItem();
        itemDeMenuPaciente = new javax.swing.JMenuItem();
        itemDeMenuProfissional = new javax.swing.JMenuItem();
        itemDeMenuUsuario = new javax.swing.JMenuItem();
        menuAjuda = new javax.swing.JMenu();
        itemDeMenuSobre = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("SisGEAC - Versã 2.0");

        menuArquivo.setMnemonic('f');
        menuArquivo.setText("Arquivo");

        itemDeMenuImportaBase.setMnemonic('o');
        itemDeMenuImportaBase.setText("Importar...");
        menuArquivo.add(itemDeMenuImportaBase);

        itemDeMenuExportaBase.setMnemonic('s');
        itemDeMenuExportaBase.setText("Exportar...");
        menuArquivo.add(itemDeMenuExportaBase);
        menuArquivo.add(jSeparator1);

        itemDeMenuSair.setMnemonic('x');
        itemDeMenuSair.setText("Sair");
        itemDeMenuSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemDeMenuSairActionPerformed(evt);
            }
        });
        menuArquivo.add(itemDeMenuSair);

        menuBar.add(menuArquivo);

        menuCadastro.setMnemonic('e');
        menuCadastro.setText("Cadastro");

        itemDeMenuExame.setText("Exame");
        menuCadastro.add(itemDeMenuExame);

        itemDeMenuCadPaciente.setMnemonic('t');
        itemDeMenuCadPaciente.setText("Paciente");
        menuCadastro.add(itemDeMenuCadPaciente);

        itemDeMenuCadProfissional.setMnemonic('y');
        itemDeMenuCadProfissional.setText("Profissional");
        menuCadastro.add(itemDeMenuCadProfissional);

        itemDeMenuCadUsuario.setMnemonic('p');
        itemDeMenuCadUsuario.setText("Usuário");
        menuCadastro.add(itemDeMenuCadUsuario);

        menuBar.add(menuCadastro);

        menuRelatorio.setText("Relatório");

        itemDeMenuGeral.setText("Geral (tipo de exame)");
        menuRelatorio.add(itemDeMenuGeral);

        itemDeMenuPaciente.setText("Paciente");
        menuRelatorio.add(itemDeMenuPaciente);

        itemDeMenuProfissional.setText("Profissional");
        menuRelatorio.add(itemDeMenuProfissional);

        itemDeMenuUsuario.setText("Usuario");
        menuRelatorio.add(itemDeMenuUsuario);

        menuBar.add(menuRelatorio);

        menuAjuda.setMnemonic('h');
        menuAjuda.setText("Ajudar");

        itemDeMenuSobre.setMnemonic('a');
        itemDeMenuSobre.setText("Sobre");
        itemDeMenuSobre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemDeMenuSobreActionPerformed(evt);
            }
        });
        menuAjuda.add(itemDeMenuSobre);

        menuBar.add(menuAjuda);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
        );

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

    private void itemDeMenuSairActionPerformed(java.awt.event.ActionEvent evt) {                                               
        System.exit(0);
    }                                                                                             

    // Variables declaration - do not modify                     
    private javax.swing.JDesktopPane desktopPane;
    private javax.swing.JMenuItem itemDeMenuCadPaciente;
    private javax.swing.JMenuItem itemDeMenuCadProfissional;
    private javax.swing.JMenuItem itemDeMenuCadUsuario;
    private javax.swing.JMenuItem itemDeMenuExame;
    private javax.swing.JMenuItem itemDeMenuExportaBase;
    private javax.swing.JMenuItem itemDeMenuGeral;
    private javax.swing.JMenuItem itemDeMenuImportaBase;
    private javax.swing.JMenuItem itemDeMenuPaciente;
    private javax.swing.JMenuItem itemDeMenuProfissional;
    private javax.swing.JMenuItem itemDeMenuSair;
    private javax.swing.JMenuItem itemDeMenuSobre;
    private javax.swing.JMenuItem itemDeMenuUsuario;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JMenu menuAjuda;
    private javax.swing.JMenu menuArquivo;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenu menuCadastro;
    private javax.swing.JMenu menuRelatorio;
    // End of variables declaration                   
    private JDesktopPane desktop;
}

A referida Classe é chamada na seguinte classe Principal:

import java.io.IOException;
import net.mastersoft.sisgeac.visao.gui.GUIPrincipal;

public class Principal {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        
        GUIPrincipal guiPrincipal = new GUIPrincipal();
        guiPrincipal.setVisible(true);
    }
}

Porque dessa forma a imagem não esta sendo carregada?

C

Tenta desse Jeito. No meu caso funcionou.

import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class Frame extends JFrame {

	private JMenuBar menuBar;
	private JMenu menu;
	private JDesktopPane desktopPane;
	private JMenuItem menuItem;
	
	private Image img;
	//private InternalFrame1 if1;
	
	public Frame() {
		super("Frame");
		//setExtendedState(MAXIMIZED_BOTH);
		setSize(400,300);
		setLocationRelativeTo(null);
		
		try{  
            img = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("gon.jpg"), "gon.jpg"));  
  		}  
      catch(Exception e){
    	  e.printStackTrace();
		}

		 desktopPane = new JDesktopPane(){
			public void paintComponent(Graphics g){  
		           super.paintComponent(g);  
		           if(img != null){  
		               g.drawImage(img, 0,0,this.getWidth(),this.getHeight(),this);  
		           }  
		           else{  
		               g.drawString("Image not found", 50,50);    
		     	   }
				}
			}; 	
		
		menuBar = new JMenuBar();
		
		setJMenuBar(menuBar);
		
		menu = new JMenu("Opções");
		menuBar.add(menu);
		
		menuItem = new JMenuItem("MenuItem");
		
		/**
		menuItem.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				if(if1 == null){
					if1 = new InternalFrame1();
					if1.setVisible(true);
					desktopPane.add(if1);
				}
				else if(!if1.isVisible()){
					if1.setVisible(true);
					desktopPane.add(if1);
				}
		}} );
		**/

		setContentPane(desktopPane);
		
		menu.add(menuItem);
	}	
	
	public static void main(String[] args) {
		Frame frame = new Frame();
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}		
}
Criado 21 de janeiro de 2012
Ultima resposta 16 de jul. de 2012
Respostas 9
Participantes 4