1

I use DefaultComboBoxModel to add specific items to my JComboBox (String text, Icon icon). But something goes wrong. When I add those two items to my combo model it looks like this:

ComboBoxWindow: 

              [icon          ]

              [icon     value]

In summary, my code for combobox looks like this:

private JComboBox combobox;
...
DefaultComboBoxModel model = new DefaultComboBoxModel();
combobox = new JComboBox(model);
...
/*
 * I use JButton for 'sending' hex value taken from JTextField to 'combobox'
 * with help of 'addToComboBox()' method
 */
 public void addToComboBox() {

    String value = field.getText().toString();     // getin' text from 'left' JTextField

    Color color = tcc.getColor();                  // getin' color from some other JLabel
    ColorSwatch icon = new ColorSwatch(10, true);  // using some custom method to create little square icon
    icon.setColor(color);     // seting color of created icon

    combobox.addItem(icon);
    combobox.addItem(value);
 }

I considered using ListCellRenderer, but I don't know how can I 'tell' it that it should render, for example, a JLabel component by using 'value' and 'icon' simultaneously. It's very important for me to have possibility to add those items dynamically by using a JButton.

enter image description here

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
bluevoxel
  • 4,978
  • 11
  • 45
  • 63
  • Dynamic add items to JComboBox (already visible) == MutableComboBoxModel – mKorbel Aug 05 '13 at 12:26
  • for better help sooner post an [SSCCE](http://sscce.org/), short, runnable, compilable, [f.i. Icon you can take from JOptionPane](http://stackoverflow.com/a/7944388/714968) – mKorbel Aug 05 '13 at 12:29
  • Well, you're adding two items through `addItem()`, so you'll get two lines... Does your `ColorSwatch` class have a `toString()` method that returns the color hexa code? – Matthieu Aug 05 '13 at 12:32
  • for basic workaround to see Oracle tutorial How to use Comboboxes, part Providing a Custom Renderer, its about ListCellRenderer – mKorbel Aug 05 '13 at 12:34
  • Oh! I know! I'll send only a hex value of the color of the icon and in ListCellRenderer I'll create JLabel with use of ColorSwatch and sended hex value. Afterall to create JLabel with specified icon and text I need just hex value of the color of the icon :D But the question is if it would be possible to add objects dynamically? : / – bluevoxel Aug 05 '13 at 12:49
  • Q---> `:D But the question is if it would be possible to add objects dynamically?` A---> yes, there I can't see any issue with that, see my commments 2nd. and then 1st. – mKorbel Aug 05 '13 at 13:10

1 Answers1

1

I did it & it works now just fine :) Basicaly 1. I've used a DefaultComboBoxModel, 2. I've added it to my JComboBox, 3. I've added a custom ListCellRenderer which 'translates' taken string (e.g. '#FFFFFF') to a icon & proper text and at the end creates a JLabel with that newborn icon and text.

/**
 * Main Class
 */
public class ColorChooser {
   ...
   public ColorChooser() {
      ...
      DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
      JComboBox combobox = new JComboBox<String>(model);
      combobox.setEditable(false);
      cobobox.setRenderer(new ComboRenderer());
      ...
   }
   ...
}

/**
 * Renderer Class
 */
public class ComboRenderer extends JLabel implements ListCellRenderer<Object> {

   public ComboRenderer() {

   }

   public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {

      setFont(newFont("Consolas", Font.PLAIN, 14));
      setOpaque(true);

      String hex;

      if (value != null) {

         /*
          * So basically I add to my 'model' in ColorChooser main class only Strings
          * which I get e.g. from some JTextField. 
          * On base of this String I create icon for future JLabel
          * and I set String 'value' as text for it.
          */
         hex = value.toString();

         Color color = HexToRgb(hex); //Method which translates String to Color

         ColorSwatch icon = new ColorSwatch(10, true); // ColorSwatch is a method which creates specific square icon (in this case a little square)
         icon.setColor(color);

         setText(hex);
         setIcon(icon);
      }
      return this;
   }

   /*
    * My translate method which translates given String to a specific color value
    * (RGB/RGBA)
    */
   public Color HexToRgb(String colorStr) {

      Color color = null;

      // For String hex value '#RRGGBB'
      if (colorStr.length() == 7) {

         color = new Color(
            Integer.valueOf(colorStr.substring(1, 3), 16),
            Integer.valueOf(colorStr.substring(3, 5), 16),
            Integer.valueOf(colorStr.substring(5, 7), 16));

        // For String hex value '#AARRGGBB'
      } else if (colorStr.length() == 9) {

         color = new Color(
            Integer.valueOf(colorStr.substring(3, 5), 16),
            Integer.valueOf(colorStr.substring(5, 7), 16),
            Integer.valueOf(colorStr.substring(7, 9), 16),
            Integer.valueOf(colorStr.substring(1, 3), 16));

        // For String hex value '0xRRGGBB'
      } else if (colorStr.length() == 8) {

         color = new Color(
            Integer.valueOf(colorStr.substring(2, 4), 16),
            Integer.valueOf(colorStr.substring(4, 6), 16),
            Integer.valueOf(colorStr.substring(6, 8), 16));

        // For String hex value '0xAARRGGBB'
      } else if (colorStr.length() == 10) {

         color = new Color(
            Integer.valueOf(colorStr.substring(4, 6), 16),
            Integer.valueOf(colorStr.substring(6, 8), 16),
            Integer.valueOf(colorStr.substring(8, 10), 16),
            Integer.valueOf(colorStr.substring(2, 4), 16));

      } else
         JOptionPane.showMessageDialog(null, "Something wen wrong... :|");

      return color;
   }
}

And with renderer like this I can just add items to my combobox...

try {

   String hex = jtextfield.getText();
   boolean canI = CheckHexValue(hex); //Method for checkin' if 'hex' String fits some specific terms

   if (canI) {

      combobox.insertItemAt(hex, 0);
      combobox.setSelectedIndex(0);
   }
} catch (Exception e) {
   JOptionPane.showMessageDialog(null, e);
}

...and we are home now. Hope that code will help someone :)

bluevoxel
  • 4,978
  • 11
  • 45
  • 63