简体   繁体   中英

Getting values from JComboBox upon selection and deselection

I am trying to display a selected item from a JComboBox (which I do get to display) but when I pass a ItemListener to see if it was deselected, the other label still shows up and it just overlaps the next label. Here is my code:

ItemListener itemListener = new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent event) {
        int state = event.getStateChange();

        JPanel select = new JPanel();

        JLabel label = new JLabel("Department Selected: ");

        JTextField selected = new JTextField(10);

        switch (state) {
            case ItemEvent.SELECTED:
                String selection = (String) aDpts.getSelectedItem();
                selected.setEditable(false);
                selected.setText(selection);

                select.add(label);
                select.add(selected);

            break;

            case ItemEvent.DESELECTED:
                label.removeAll();
                selected.removeAll();
                select.removeAll();
            break;
        }

        add(select, BorderLayout.LINE_END);
    }

Also, it won't show the label unless I resize the window..

You're creating a new instance of JLabel EVERY time itemStateChanged is changed, so you're attempting to remove a label from a container to which it was never added.

Instead, simply create a single JLabel and update it's text property

I'm scratching my head over why you would create a new instance of JLabel , JPanel and JTextField when it seems like you are simply trying to update the previous states

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM