Search code examples
javaswingjcombobox

How to get an input from two different combo boxes?


I have to write a Java code where I should get input from 2 different combo boxes. The input, that I will get, has to be display in a text field. I have written a part of my code but I can't get the input.

This is what I have written so far:

package main;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ComboI extends JFrame implements ItemListener{
    JComboBox dita = new JComboBox();
    JComboBox ora = new JComboBox();
    JLabel dita1 = new JLabel("Zgjidhni diten:");
    JLabel ora1 = new JLabel("Zgjidhni oren");
    JTextArea pergjigje = new JTextArea(2, 10);
    public ComboI(){
        super("Orari mesimor IE102");
        setSize(600, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        Container content = getContentPane();
        FlowLayout lay = new FlowLayout(FlowLayout.LEFT);
        content.setLayout(lay);
        content.add(dita);
        content.add(dita1);
        content.add(ora1);
        content.add(ora);
        content.add(pergjigje);
        setContentPane(content);

        dita.addItem("E Hene");
        dita.addItem("E Marte");
        dita.addItem("E Merkure");
        dita.addItem("E Enjte");
        dita.addItem("E Premte");
        dita.addItemListener(this);


        ora.addItem("08:30 - 09:25");
        ora.addItem("09:30 - 10:25");
        ora.addItem("10:30 - 11:25");
        ora.addItem("11:30 - 12:25");
        ora.addItem("12:30 - 13:25");
        ora.addItem("13:30 - 14:25");
        ora.addItemListener(this);

    }
    public void itemStateChanged(ItemEvent event){
        String choice1 = event.getItem().toString();
        String choice2 = event.getItem().toString();

        if (choice1.equals("E Marte") && choice2.equals("E Marte")){
            String a = "hi";
            pergjigje.setText(a);
        }
    }
}

Solution

  • String choice1 = event.getItem().toString();
    String choice2 = event.getItem().toString();
    

    You can only generate an event for one combo box at a time, so if you want the values from the combo boxes you need to access the combo box, not the event.

    The code would be something like:

    String choice1 = dita.getSelectedItem().toString();
    String choice2 = ora.getSelectedItem().toString();