by Dinesh Thakur Category: Swing

 

import java.awt.*;

import javax.swing.*;
import java.awt.event.*;
/*<APPLET CODE = ExampleComboImagesInJavaApplet.class WIDTH = 410 HEIGHT = 210 ></APPLET>*/ 
public class ExampleComboImagesInJavaApplet extends JApplet
  {
      public void init()
       {
         Container cntnr = getContentPane();
         cntnr.setLayout(new FlowLayout());
         NewModel NwMdl = new NewModel();
         NewRenderer NwRndrer = new NewRenderer();
         JComboBox JLst = new JComboBox(NwMdl);
         JLst.setRenderer(NwRndrer);
         cntnr.add(new JScrollPane(JLst));
       }
  }
        class NewModel extends DefaultComboBoxModel
         {
            public NewModel()
            {
               for(int loop_index = 0; loop_index <= 12; loop_index++)
                   {
                       addElement(new Object[] {"Item " + loop_index,new ImageIcon("Koala.jpg")});
                   }
            }
        }
                 class NewRenderer extends JLabel implements ListCellRenderer
                     {
                        public NewRenderer()
                         {
                            setOpaque(true);
                         }
                           public Component getListCellRendererComponent(JList Jlst, Object ob1, int indx, boolean isSelected,boolean focus)
                             {
                                NewModel Mdl = (NewModel)Jlst.getModel();
                                setText((String)((Object[])ob1)[0]);
                                setIcon((Icon)((Object[])ob1)[1]);
                                if(!isSelected)
                         {
                                     setBackground(Jlst.getBackground());
                                     setForeground(Jlst.getForeground());
                                 }
                                   else
                                      {
                                         setBackground(Jlst.getSelectionBackground());
                                        setForeground(Jlst.getSelectionForeground());
                                      }
                                         return this;
                            }
                     }

Image in JCombox Java Swing Example

Popular Article