Search code examples
comboboxreturn-valuejdialog

Java JDialog: How to return item (object) selected from a combobox


I have created a jdialog which contains a combobox (see photo ).

The combobox contains items of Delivery class. The date you see in the photo is the value returns from Delivery.toString().

When i press OK, i need to return the Delivery object that is selected from the combobox, to the parent form.


Solution

  • You could use something along the lines of:

        public BillatoDialog extends JDialog(){
           private Delivery selectedDelivery; // Declare selectedDelivery variable
    
           String selectedDate = comboBox.getSelectedItem();    // Returns the current selected item.
           for (Delivery currentDelivery: deliveryList){        // Loop over a list with all the deliverys. 
              if (currentDelivery.toString()==selectedDate;){  // and break the for when match found.
              selectedDelivery = currentDelivery;          // assign it to selectedDelivery
              break;
              }
           }
    
          public Delivery getSelectedDelivery(){
             return selectedDelivery;
          }
    }
    

    And then in your JPanel

    public BillatoPanel extends JPanel(){
       openBillatoDialog();
       getSelectedDelivery();
    }