Search code examples
javaswingjcomboboxcomboboxmodel

Allow JComboBox to accept List<String> or HashMap instead of String[]


When inputting a new Student object inside my JTables I would like to hold all the localities/cities inside my JComboBox. Each city is stored inside a HashMap which holds the name as key(as there are no duplicates) and it's postcode.

Example: hashMap.put("City", "AAA")

Now my issue would be to represent the HashMap OR List<String> inside the JComboBox itself. The cheap and easy alternative was to simply re-write the String[] to hold all the town names and switch-case the selected value but there are few issues with that:

  1. It's too long, adding new localities may be a pain or waste of time
  2. Alot of unnecessary code
  3. Looks horrible if being reviewed by someone
  4. Potentially slower than my proposed method

Solution

  • Here you go :

     String [] string = {"city","town","country","province"};
     java.util.List<String> list = new ArrayList<String>(Arrays.asList(string));
    
    
     Object[] arrayObject= list.toArray();
     String [] data = Arrays.copyOf(arrayObject, arrayObject.length,String[].class); // java 1.6+
     JComboBox<String> combo = new JComboBox<>( data);
    

    Actually you can do :

     String [] string = {"city","town","country","province"};
     java.util.List<String> list = new ArrayList<String>(Arrays.asList(string));
    
    
     JComboBox< java.util.List<String>> combo = new JComboBox<>( );
     combo.addItem(list);
    

    but , for every single elemen of JComboxBox will hold all elements of list in a row.

    *To prevent ambiguity between java.util.List & java.awt.List , we should declare them clearly.

    Here the complete demo :

    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    
    public class ComboBoxDemo extends JFrame {
    public ComboBoxDemo() {
    
      super("JComboBox Demo");
    
        String [] string = {"city","town","country","province"};
      java.util.List<String> list = new ArrayList<String>(Arrays.asList(string));
    
    
     Object[] arrayObject= list.toArray();
     String [] data = Arrays.copyOf(arrayObject, arrayObject.length,String[].class); // java 1.6+
     JComboBox<String> combo = new JComboBox<>( data);
    
        setLayout(new FlowLayout(FlowLayout.CENTER));
        add(combo, BorderLayout.CENTER);      
    }
    
     public static void main(String[] args) {
          ComboBoxDemo g = new ComboBoxDemo();
        g.setVisible(true);
        g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        g.setBounds(100, 100, 300, 300);
     }
     }
    

    enter image description here

    And the result of

    JComboBox< java.util.List<String>> combo = new JComboBox<>( ); combo.addItem(list);

    declaration :

    enter image description here