0

Developing a simple java GUI application using swing.

I have a ArrayList fetched from a file. How do I display that as a drop down for the user to select. And how to obtain the object which the user has selected.??

Any suggestions will be greatly appreciated.

0

4 Answers 4

2

This link should help you to create the drop down menu: http://www.java2s.com/Code/Java/Swing-JFC/Usingdropdownlists.htm

In the part where you insert items in your menu just loop throught your ArrayList items and select them one by one.

for (int i = 0; i < list.size(); i++) {
    //insert in menu .. list.get(i); 
}

The actionlistener will take care of the action. ie to know wich element was selected.

Some more info here: https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

2

This is an example for using a fixed string array. It is a fairly simple extrapolation from this code to an arrayList imported from a file:

// define items in a String array:
    String[] languages = new String[] {"English", "French", "Spanish", "Japanese", "Chinese"};

    // create a combo box with the fixed array:
    JComboBox<String> comboLanguage = new JComboBox<String>(languages);
2

Look at JComboBox's constructors. You can supply a ComboBoxModel, an array, or a Vector. If you have a List then just create a new Vector from it.

new JComboBox(new Vector(list));

If you want your combobox to dynamically change then you'll need to use a ComboBoxModel.

1

If you have a collection of objects and want to display a value, you can use the Vector class as the model and then create a custom renderer using the BasicComboBoxRenderer class to display the text.

    Vector<Employee> data = new Vector<Employee>();
    data.addElement(new Employee(1001, "John Smith"));
    data.addElement(new Employee(1002, "Linda Baker"));
    data.addElement(new Employee(1003, "Youcef Hussain"));
    data.addElement(new Employee(1004, "Jia Lia"));

    JComboBox jcb = new JComboBox(data);
    jcb.setRenderer(new ComboBoxRenderer());

class ComboBoxRenderer extends javax.swing.plaf.basic.BasicComboBoxRenderer
{
    public Component getListCellRendererComponent(JList list,Object value,int index,boolean isSelected,boolean cellHasFocus)
    {
        Employee emp = (Employee)value;
        setText(emp.getName());
        return this;
    }
}

class Employee{
    protected int employee_id;
    public String employee_name;

    public Employee(int id, String name){
        this.employee_id = id;
        this.employee_name = name;
    }

    public String getName(){
        return this.employee_name;
    }
}

Full code sample can be found here http://www.hostprojects.net/snippets/java/158/basiccomboboxrenderer-example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.