Search code examples
javalabelawtselectedvalue

Display list selected value on label


ItemListener is implemented here, below code is just the part. Here, i need the selected item from the list to be displayed on the label. This code isn't working. Thankyou for helping.

public void itemStateChanged(ItemEvent ie)
{
    String data = objectOfList.getSelectedItem();
    objectOfLabel.setText("selected item: " + data);
}

Solution

  • You want to add an item listener to the combobox whose itemStateChanged() method gets called each time the user selects or deselects an item.

    https://docs.oracle.com/javase/7/docs/api/java/awt/event/ItemListener.html#itemStateChanged(java.awt.event.ItemEvent)

    I've written a small demo you can use as a reference:

    public static void main(String[] args) {
        JComboBox<String> comboBox = new JComboBox<>();
        comboBox.addItem("item1");
        comboBox.addItem("item2");
    
        JLabel label = new JLabel();
    
        comboBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                label.setText("selected item: " + comboBox.getSelectedItem());
            }
        });
    
        JPanel panel = new JPanel();
        panel.add(label);
        panel.add(comboBox);
    
        JFrame frame = new JFrame();
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }