Adicionar imagem a jComboBox

5 respostas
R

Boas eu estava a seguir o exemplo do site da sun (o Providing a Custom Renderer)

http://download.oracle.com/javase/tutorial/uiswing/components/combobox.html

e estava a tentar adapta-lo para só preencher a jcombobox quando se carrega num botão
mas o meu código está-me a devolver uma excepção:

Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException

at CustomComboBoxDemo$ComboBoxRenderer.getListCellRendererComponent(CustomComboBoxDemo.java:180)

at javax.swing.plaf.basic.BasicComboBoxUI.paintCurrentValue(BasicComboBoxUI.java:1214)

at javax.swing.plaf.metal.MetalComboBoxUI.paintCurrentValue(MetalComboBoxUI.java:90)

at javax.swing.plaf.basic.BasicComboBoxUI.paint(BasicComboBoxUI.java:905)

at javax.swing.plaf.metal.MetalComboBoxUI.paint(MetalComboBoxUI.java:62)

at javax.swing.plaf.ComponentUI.update(ComponentUI.java:161)

at javax.swing.JComponent.paintComponent(JComponent.java:778)

at javax.swing.JComponent.paint(JComponent.java:1054)

at javax.swing.JComponent.paintToOffscreen(JComponent.java:5221)

at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:295)

at javax.swing.RepaintManager.paint(RepaintManager.java:1206)

at javax.swing.JComponent._paintImmediately(JComponent.java:5169)

at javax.swing.JComponent.paintImmediately(JComponent.java:4980)

at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:770)

at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:728)

at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:677)

at javax.swing.RepaintManager.access$700(RepaintManager.java:59)

at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1621)

at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)

at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)

at java.awt.EventQueue.access$000(EventQueue.java:101)

at java.awt.EventQueue$3.run(EventQueue.java:666)

at java.awt.EventQueue$3.run(EventQueue.java:664)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)

at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

Em seguida coloco o meu código

/*
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle or the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/*
 * CustomComboBoxDemo.java uses the following files:
 *   images/Bird.gif
 *   images/Cat.gif
 *   images/Dog.gif
 *   images/Rabbit.gif
 *   images/Pig.gif
 */
public class CustomComboBoxDemo extends JPanel {
    ImageIcon[] images ;
    String[] alarms = {"Bird", "Cat", "Dog", "Rabbit", "Pig"};
    JComboBox petList;
    ListCellRenderer aaa;
    /*
     * Despite its use of EmptyBorder, this panel makes a fine content
     * pane because the empty border just increases the panel's size
     * and is "painted" on top of the panel's normal background.  In
     * other words, the JPanel fills its entire background if it's
     * opaque (which it is by default); adding a border doesn't change
     * that.
     */
    public CustomComboBoxDemo() {
        super(new BorderLayout());
        this.setSize(new Dimension(300,300));
        //Load the pet images and create an array of indexes.
        images = new ImageIcon[alarms.length];
        /*Integer[] intArray = new Integer[alarms.length];
        for (int i = 0; i < alarms.length; i++) {
            intArray[i] = new Integer(i);
            images[i] = new ImageIcon("images/"+alarms[i]+".gif");
            if (images[i] != null) {
                images[i].setDescription(alarms[i]);
            }
        }*/

        //Create the combo box.
        petList = new JComboBox(/*intArray*/);
        //petList.setVisible(false);
        aaa = petList.getRenderer();
        /*ComboBoxRenderer renderer= new ComboBoxRenderer(images,alarms);
        renderer.setPreferredSize(new Dimension(200, 130));
        petList.setRenderer(renderer);*/
        petList.setMaximumRowCount(3);

        //Lay out the demo.*/
        add(petList, BorderLayout.PAGE_START);
        JButton sdf =new JButton("SSS");
        OptionsNavigationListener opt_action = new OptionsNavigationListener();
        sdf.addActionListener(opt_action);
        add(sdf);
        //setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
        //System.out.println(petList.getItemAt(1));
    }

    class OptionsNavigationListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            //System.out.println("sdf");
            //
            petList.setVisible(true);
            petList.setRenderer(aaa);
            petList.removeAllItems();
            images = new ImageIcon[alarms.length];
            Integer[] intArray = new Integer[alarms.length];
            for (int i = 0; i < alarms.length; i++) {
                intArray[i] = new Integer(i);
                images[i] = new ImageIcon("images/"+alarms[i]+".gif");
                if (images[i] != null) {
                    images[i].setDescription(alarms[i]);
                }
                petList.insertItemAt(intArray[i], petList.getItemCount());
                
            }
            ComboBoxRenderer renderer2= new ComboBoxRenderer(images,alarms);
            //renderer.setPreferredSize(new Dimension(200, 130));
            if (renderer2 != null){
                System.out.println("mer......"+renderer2);
                renderer2.setPreferredSize(new Dimension(200, 130));
            }
            petList.setRenderer(renderer2);
        }
        
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("CustomComboBoxDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new CustomComboBoxDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    class ComboBoxRenderer extends JLabel
                           implements ListCellRenderer {

private ImageIcon[] images;
private String[] alarms;

        public ComboBoxRenderer(ImageIcon[] images, String[] alarms) {
            setOpaque(true);
            setHorizontalAlignment(CENTER);
            setVerticalAlignment(CENTER);
            this.alarms = alarms;
            this.images = images;
        }

        /*
         * This method finds the image and text corresponding
         * to the selected value and returns the label, set up
         * to display the text and image.
         */
        @Override
        public Component getListCellRendererComponent(
                                           JList list,
                                           Object value,
                                           int index,
                                           boolean isSelected,
                                           boolean cellHasFocus) {
            //Get the selected index. (The index param isn't
            //always valid, so just use the value.)
           
                int selectedIndex = ((Integer)value).intValue();

                if (isSelected) {
                    setBackground(list.getSelectionBackground());
                    setForeground(list.getSelectionForeground());
                } else {
                    setBackground(list.getBackground());
                    setForeground(list.getForeground());
                }

                //Set the icon and text.  If icon was null, say so.
                ImageIcon icon = images[selectedIndex];
                String pet = alarms[selectedIndex];
                setIcon(icon);
                if (icon != null) {
                    setText(pet);
                    setFont(list.getFont());
                } else{
                    System.out.println("sdf " + selectedIndex);
                }
            
            return this;
        }

        //Set the font and text when no image was found.

    }
}

obrigado pela ajuda

5 Respostas

AndreSorge

roybean, Boa tarde!

Copiei o seu código, e executei normalmente, o único problema é com a annotation @Override, que no caso serve para sobrescrever o método, e voce está implementando a classe então não existe essa annotation.

Tente tirar essas anotações e ve se funciona…tente executar esse código…

package tela;

/* 
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. 
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions 
 * are met: 
 * 
 *   - Redistributions of source code must retain the above copyright 
 *     notice, this list of conditions and the following disclaimer. 
 * 
 *   - Redistributions in binary form must reproduce the above copyright 
 *     notice, this list of conditions and the following disclaimer in the 
 *     documentation and/or other materials provided with the distribution. 
 * 
 *   - Neither the name of Oracle or the names of its 
 *     contributors may be used to endorse or promote products derived 
 *     from this software without specific prior written permission. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */   
   
 import java.awt.*;  
 import java.awt.event.*;  
 import javax.swing.*;  
   
 /* 
 * CustomComboBoxDemo.java uses the following files: 
 *   images/Bird.gif 
 *   images/Cat.gif 
 *   images/Dog.gif 
 *   images/Rabbit.gif 
 *   images/Pig.gif 
 */  
 public class CustomComboBoxDemo extends JPanel {  
     ImageIcon[] images ;  
     String[] alarms = {"Bird", "Cat", "Dog", "Rabbit", "Pig"};  
     JComboBox petList;  
     ListCellRenderer aaa;  
     /* 
      * Despite its use of EmptyBorder, this panel makes a fine content 
      * pane because the empty border just increases the panel's size 
      * and is "painted" on top of the panel's normal background.  In 
      * other words, the JPanel fills its entire background if it's 
      * opaque (which it is by default); adding a border doesn't change 
      * that. 
      */  
     public CustomComboBoxDemo() {  
         super(new BorderLayout());  
         this.setSize(new Dimension(300,300));  
         //Load the pet images and create an array of indexes.  
         images = new ImageIcon[alarms.length];  
         /*Integer[] intArray = new Integer[alarms.length]; 
         for (int i = 0; i < alarms.length; i++) { 
             intArray[i] = new Integer(i); 
             images[i] = new ImageIcon("images/"+alarms[i]+".gif"); 
             if (images[i] != null) { 
                 images[i].setDescription(alarms[i]); 
             } 
         }*/  
   
         //Create the combo box.  
         petList = new JComboBox(/*intArray*/);  
         //petList.setVisible(false);  
         aaa = petList.getRenderer();  
         /*ComboBoxRenderer renderer= new ComboBoxRenderer(images,alarms); 
         renderer.setPreferredSize(new Dimension(200, 130)); 
         petList.setRenderer(renderer);*/  
         petList.setMaximumRowCount(3);  
   
         //Lay out the demo.*/  
         add(petList, BorderLayout.PAGE_START);  
         JButton sdf =new JButton("SSS");  
         OptionsNavigationListener opt_action = new OptionsNavigationListener();  
         sdf.addActionListener(opt_action);  
         add(sdf);  
         //setBorder(BorderFactory.createEmptyBorder(20,20,20,20));  
         //System.out.println(petList.getItemAt(1));  
     }  
   
     class OptionsNavigationListener implements ActionListener {  
   
         public void actionPerformed(ActionEvent e) {  
             //System.out.println("sdf");  
             //  
             petList.setVisible(true);  
             petList.setRenderer(aaa);  
             petList.removeAllItems();  
             images = new ImageIcon[alarms.length];  
             Integer[] intArray = new Integer[alarms.length];  
             for (int i = 0; i < alarms.length; i++) {  
                 intArray[i] = new Integer(i);  
                 images[i] = new ImageIcon("images/"+alarms[i]+".gif");  
                 if (images[i] != null) {  
                     images[i].setDescription(alarms[i]);  
                 }  
                 petList.insertItemAt(intArray[i], petList.getItemCount());  
                   
             }  
             ComboBoxRenderer renderer2= new ComboBoxRenderer(images,alarms);  
             //renderer.setPreferredSize(new Dimension(200, 130));  
             if (renderer2 != null){  
                 System.out.println("mer......"+renderer2);  
                 renderer2.setPreferredSize(new Dimension(200, 130));  
             }  
             petList.setRenderer(renderer2);  
         }  
           
     }  
   
     /** 
      * Create the GUI and show it.  For thread safety, 
      * this method should be invoked from the 
      * event-dispatching thread. 
      */  
     private static void createAndShowGUI() {  
         //Create and set up the window.  
         JFrame frame = new JFrame("CustomComboBoxDemo");  
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
   
         //Create and set up the content pane.  
         JComponent newContentPane = new CustomComboBoxDemo();  
         newContentPane.setOpaque(true); //content panes must be opaque  
         frame.setContentPane(newContentPane);  
   
         //Display the window.  
         frame.pack();  
         frame.setVisible(true);  
     }  
   
     public static void main(String[] args) {  
         //Schedule a job for the event-dispatching thread:  
         //creating and showing this application's GUI.  
         javax.swing.SwingUtilities.invokeLater(new Runnable() {  
             public void run() {  
                 createAndShowGUI();  
             }  
         });  
     }  
   
     class ComboBoxRenderer extends JLabel  
                            implements ListCellRenderer {  
   
 private ImageIcon[] images;  
 private String[] alarms;  
   
         public ComboBoxRenderer(ImageIcon[] images, String[] alarms) {  
             setOpaque(true);  
             setHorizontalAlignment(CENTER);  
             setVerticalAlignment(CENTER);  
             this.alarms = alarms;  
             this.images = images;  
         }  
   
         /* 
          * This method finds the image and text corresponding 
          * to the selected value and returns the label, set up 
          * to display the text and image. 
          */  
         public Component getListCellRendererComponent(  
                                            JList list,  
                                            Object value,  
                                            int index,  
                                            boolean isSelected,  
                                            boolean cellHasFocus) {  
             //Get the selected index. (The index param isn't  
             //always valid, so just use the value.)  
              
                 int selectedIndex = ((Integer)value).intValue();  
   
                 if (isSelected) {  
                     setBackground(list.getSelectionBackground());  
                     setForeground(list.getSelectionForeground());  
                 } else {  
                     setBackground(list.getBackground());  
                     setForeground(list.getForeground());  
                 }  
   
                 //Set the icon and text.  If icon was null, say so.  
                 ImageIcon icon = images[selectedIndex];  
                 String pet = alarms[selectedIndex];  
                 setIcon(icon);  
                 if (icon != null) {  
                     setText(pet);  
                     setFont(list.getFont());  
                 } else{  
                     System.out.println("sdf " + selectedIndex);  
                 }  
               
             return this;  
         }  
   
         //Set the font and text when no image was found.  
   
     }  
 }
AndreSorge

Boa Tarde Roybean,

Tenta executar dessa maneira…

package tela;

/* 
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. 
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions 
 * are met: 
 * 
 *   - Redistributions of source code must retain the above copyright 
 *     notice, this list of conditions and the following disclaimer. 
 * 
 *   - Redistributions in binary form must reproduce the above copyright 
 *     notice, this list of conditions and the following disclaimer in the 
 *     documentation and/or other materials provided with the distribution. 
 * 
 *   - Neither the name of Oracle or the names of its 
 *     contributors may be used to endorse or promote products derived 
 *     from this software without specific prior written permission. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */   
   
 import java.awt.*;  
 import java.awt.event.*;  
 import javax.swing.*;  
   
 /* 
 * CustomComboBoxDemo.java uses the following files: 
 *   images/Bird.gif 
 *   images/Cat.gif 
 *   images/Dog.gif 
 *   images/Rabbit.gif 
 *   images/Pig.gif 
 */  
 public class CustomComboBoxDemo extends JPanel {  
     ImageIcon[] images ;  
     String[] alarms = {"Bird", "Cat", "Dog", "Rabbit", "Pig"};  
     JComboBox petList;  
     ListCellRenderer aaa;  
     /* 
      * Despite its use of EmptyBorder, this panel makes a fine content 
      * pane because the empty border just increases the panel's size 
      * and is "painted" on top of the panel's normal background.  In 
      * other words, the JPanel fills its entire background if it's 
      * opaque (which it is by default); adding a border doesn't change 
      * that. 
      */  
     public CustomComboBoxDemo() {  
         super(new BorderLayout());  
         this.setSize(new Dimension(300,300));  
         //Load the pet images and create an array of indexes.  
         images = new ImageIcon[alarms.length];  
         /*Integer[] intArray = new Integer[alarms.length]; 
         for (int i = 0; i < alarms.length; i++) { 
             intArray[i] = new Integer(i); 
             images[i] = new ImageIcon("images/"+alarms[i]+".gif"); 
             if (images[i] != null) { 
                 images[i].setDescription(alarms[i]); 
             } 
         }*/  
   
         //Create the combo box.  
         petList = new JComboBox(/*intArray*/);  
         //petList.setVisible(false);  
         aaa = petList.getRenderer();  
         /*ComboBoxRenderer renderer= new ComboBoxRenderer(images,alarms); 
         renderer.setPreferredSize(new Dimension(200, 130)); 
         petList.setRenderer(renderer);*/  
         petList.setMaximumRowCount(3);  
   
         //Lay out the demo.*/  
         add(petList, BorderLayout.PAGE_START);  
         JButton sdf =new JButton("SSS");  
         OptionsNavigationListener opt_action = new OptionsNavigationListener();  
         sdf.addActionListener(opt_action);  
         add(sdf);  
         //setBorder(BorderFactory.createEmptyBorder(20,20,20,20));  
         //System.out.println(petList.getItemAt(1));  
     }  
   
     class OptionsNavigationListener implements ActionListener {  
   
         public void actionPerformed(ActionEvent e) {  
             //System.out.println("sdf");  
             //  
             petList.setVisible(true);  
             petList.setRenderer(aaa);  
             petList.removeAllItems();  
             images = new ImageIcon[alarms.length];  
             Integer[] intArray = new Integer[alarms.length];  
             for (int i = 0; i < alarms.length; i++) {  
                 intArray[i] = new Integer(i);  
                 images[i] = new ImageIcon("images/"+alarms[i]+".gif");  
                 if (images[i] != null) {  
                     images[i].setDescription(alarms[i]);  
                 }  
                 petList.insertItemAt(intArray[i], petList.getItemCount());  
                   
             }  
             ComboBoxRenderer renderer2= new ComboBoxRenderer(images,alarms);  
             //renderer.setPreferredSize(new Dimension(200, 130));  
             if (renderer2 != null){  
                 System.out.println("mer......"+renderer2);  
                 renderer2.setPreferredSize(new Dimension(200, 130));  
             }  
             petList.setRenderer(renderer2);  
         }  
           
     }  
   
     /** 
      * Create the GUI and show it.  For thread safety, 
      * this method should be invoked from the 
      * event-dispatching thread. 
      */  
     private static void createAndShowGUI() {  
         //Create and set up the window.  
         JFrame frame = new JFrame("CustomComboBoxDemo");  
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
   
         //Create and set up the content pane.  
         JComponent newContentPane = new CustomComboBoxDemo();  
         newContentPane.setOpaque(true); //content panes must be opaque  
         frame.setContentPane(newContentPane);  
   
         //Display the window.  
         frame.pack();  
         frame.setVisible(true);  
     }  
   
     public static void main(String[] args) {  
         //Schedule a job for the event-dispatching thread:  
         //creating and showing this application's GUI.  
         javax.swing.SwingUtilities.invokeLater(new Runnable() {  
             public void run() {  
                 createAndShowGUI();  
             }  
         });  
     }  
   
     class ComboBoxRenderer extends JLabel  
                            implements ListCellRenderer {  
   
 private ImageIcon[] images;  
 private String[] alarms;  
   
         public ComboBoxRenderer(ImageIcon[] images, String[] alarms) {  
             setOpaque(true);  
             setHorizontalAlignment(CENTER);  
             setVerticalAlignment(CENTER);  
             this.alarms = alarms;  
             this.images = images;  
         }  
   
         /* 
          * This method finds the image and text corresponding 
          * to the selected value and returns the label, set up 
          * to display the text and image. 
          */  
         public Component getListCellRendererComponent(  
                                            JList list,  
                                            Object value,  
                                            int index,  
                                            boolean isSelected,  
                                            boolean cellHasFocus) {  
             //Get the selected index. (The index param isn't  
             //always valid, so just use the value.)  
              
                 int selectedIndex = ((Integer)value).intValue();  
   
                 if (isSelected) {  
                     setBackground(list.getSelectionBackground());  
                     setForeground(list.getSelectionForeground());  
                 } else {  
                     setBackground(list.getBackground());  
                     setForeground(list.getForeground());  
                 }  
   
                 //Set the icon and text.  If icon was null, say so.  
                 ImageIcon icon = images[selectedIndex];  
                 String pet = alarms[selectedIndex];  
                 setIcon(icon);  
                 if (icon != null) {  
                     setText(pet);  
                     setFont(list.getFont());  
                 } else{  
                     System.out.println("sdf " + selectedIndex);  
                 }  
               
             return this;  
         }  
   
         //Set the font and text when no image was found.  
   
     }  
 }
R

boa tarde AndreSorge, primeiro obrigado pela ajuda.

copiei os códigos de ambos os posts e o resultado foi o mesmo quando carrego no botão dá-me aquela excepção.

consigo correr sem a excepção desde que faça petList.setSelectedIndex(0); no fim da ação do botão.

Já agora peço já desculpa pela pergunta NOOd mas pensava que a anotaºção de overrride era apenas uma indicação e que não tinha nenhuma acção em concreto :blush:

AndreSorge

Opa, realmente não faz diferença, mas como você está implementando o @Override não está certo, somente para sobrescreta…

então aqui ele reclamou, pois o eclipse não deixa colocar a annotation @Override se você não estiver extendendo…

AndreSorge

roybean, boa Tarde

ta estourando mesmo, desculpa eu não tinha reparado no console, estou debugando para ver se te ajudo…

Criado 21 de setembro de 2011
Ultima resposta 21 de set. de 2011
Respostas 5
Participantes 2