0

I hope someone can help me out. Iam trying to create a "countrycombobox" with icons in Java Swing. I found some stuff, but nothing did work for me. Maybe the problem is, that Iam still "new" to Java. I just want it simple like this: http://www.zomex.com/libs/images/layout/whmcs-template-language-select-w-flags-eco.jpg Just the flags in front of the countrys.

I would really appreciate a working example. I really wonder, that there is no standard option or a good code snippet(used Google a lot to find help here) for stuff like this.

Hemang
  • 26,840
  • 19
  • 119
  • 186
Aca
  • 33
  • 7
  • *"I would really appreciate a working example."* We would appreciate a specific question, as well as attempts on your part. Voting to close, as SO is not a code generation machine. – Andrew Thompson Jan 21 '15 at 11:05
  • Having said (and voted) that, you want to look to the renderer for the combo box. If a `JLabel` is used, it is possible to set both text (the country name) and an icon (the flag). I would tend to encapsulate the name and flag icon in a `Country` class and store `Country` objects in the combo list. – Andrew Thompson Jan 21 '15 at 11:08
  • Hey, I tried a lot, best source I found, was "http://www.codejava.net/java-se/swing/create-custom-gui-for-jcombobox". But that didnt work for me and I didnt get why... Where is my question not specific enought? Its just "How can I add a icon to an combobox?" :) – Aca Jan 21 '15 at 11:46
  • *"Where is my question not specific enought?"* That is the first question you've asked. The 'question' above does not contain a question, only your requirement and that you would appreciate a working example. – Andrew Thompson Jan 22 '15 at 01:41

1 Answers1

1

I found a better example and wanna share my stuff with you. There is just one problem left, that I dont get it sized.

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

public class CountryComboBox extends JPanel {
    ImageIcon[] images;
    String[] imgStrings = {"de"};

    /*
     * 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 CountryComboBox() {
        super(new BorderLayout());

        //Load the images and create an array of indexes.
        images = new ImageIcon[imgStrings.length];
        Integer[] intArray = new Integer[imgStrings.length];
        for (int i = 0; i < imgStrings.length; i++) {
            intArray[i] = new Integer(i);
            images[i] = createImageIcon("/res/" + imgStrings[i] + ".png");
            if (images[i] != null) {
                images[i].setDescription(imgStrings[i]);
            }
        }

        //Create the combo box.
        JComboBox imgList = new JComboBox(intArray);
        ComboBoxRenderer renderer= new ComboBoxRenderer();
        imgList.setRenderer(renderer);
        imgList.setMaximumRowCount(3);

        //Lay out the demo.
        add(imgList, BorderLayout.PAGE_START);
        //setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
    }

    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = CountryComboBox.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
                return null;
        }
    }

    class ComboBoxRenderer extends JLabel
                           implements ListCellRenderer {
        private Font uhOhFont;

        public ComboBoxRenderer() {
            setOpaque(true);
            setHorizontalAlignment(CENTER);
            setVerticalAlignment(CENTER);
        }

        /*
         * 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 img = imgStrings[selectedIndex];
            setIcon(icon);
            if (icon != null) {
                setText(img);
                setFont(list.getFont());
            } else {
                setUhOhText(img + " (no image available)",
                            list.getFont());
            }

            return this;
        }

        //Set the font and text when no image was found.
        protected void setUhOhText(String uhOhText, Font normalFont) {
            if (uhOhFont == null) { //lazily create this font
                uhOhFont = normalFont.deriveFont(Font.ITALIC);
            }
            setFont(uhOhFont);
            setText(uhOhText);
        }
    }
}

I call it in a JPanel with absolute layout:

JComponent newContentPane = new CountryComboBox();
newContentPane.setOpaque(true); //content panes must be opaque
newContentPane.setBounds(10, 75, 50, 26);
contentPane.add(newContentPane);

setBounds isnt working, just to get the right position. I cant size it with this.

Best regards Acanis

Marcel
  • 1,509
  • 1
  • 17
  • 39
Aca
  • 33
  • 7
  • *"I call it in a JPanel with absolute layout:"* Java GUIs have to work on different OS', screen size, screen resolution etc. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Jan 22 '15 at 01:38
  • Well, I tried it first... But I didnt get the right positions with any layout manager... Which one should I learn to use for those stuff :)? – Aca Jan 23 '15 at 06:53
  • *"with any layout manager."* No layout manager can do all things well. I typically mix together around 2-4 layout managers per view, & sometimes significantly more. If you cannot figure how to layout a GUI, ask about it. When doing so, provide ASCII art or a simple drawing of the layout of the GUI at minimum size, and if resizable, with more width and height. – Andrew Thompson Jan 23 '15 at 06:57
  • *"Which one should I learn to use for those stuff :)?"* ***All*** of them (though you might skip `GroupLayout`, since it is better suited to IDE based GUI design). See [How to Use Various Layout Managers](http://docs.oracle.com/javase/tutorial/uiswing/layout/layoutlist.html) for the best tutorial on them. – Andrew Thompson Jan 23 '15 at 07:03
  • Well, thanks :) Got a nice GUI now, with FormLayout as basic and some other stuff...^^ – Aca Jan 23 '15 at 22:06