Hi
in the following program, Im trying to add some items to Jlist using JComboBox without any duplicates.
I managed to add items with Duplicates, As well as I managed to find duplicates using this condition (combo.getSelectedItem().equals(listModel.getEleme ntAt(i)) )
But when i add else statement, program didnt wiork. Please help me to understand where is the error of this program,
Thank you in advance.
import java.awt.*; import javax.swing.*; import java.awt.event.*; class Jlist5 extends JFrame implements ItemListener{ private DefaultComboBoxModel comboModel; private DefaultListModel listModel; private JList list; private JComboBox combo; private JPanel JP1; Jlist5(){ super("Option Form 1"); JFrame f1 = new JFrame(); setSize(100,00); setLocationRelativeTo(null); setDefaultCloseOperation(f1.EXIT_ON_CLOSE); JP1 = new JPanel(); JP1.setLayout(new FlowLayout()); combo = new JComboBox(); combo.addItemListener(this); listModel = new DefaultListModel(); list = new JList(listModel); JScrollPane scroll = new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scroll.setPreferredSize(new Dimension(250,150)); String []ary1 = {"Item 1111","Item 2222","Item 3333","Item 4444","Item 5555"}; for (int i = 0; i <ary1.length ; i++) { combo.addItem(ary1[i]); } JP1.add(combo); JP1.add(scroll); add(JP1); pack(); } public void itemStateChanged(ItemEvent e){ if(!(e.getStateChange()== ItemEvent.SELECTED)){ for (int i = 0; i < listModel.getSize(); i++) { if (combo.getSelectedItem().equals(listModel.getElementAt(i))) { JOptionPane.showMessageDialog(null,"Duplicate"); }else listModel.addElement(combo.getSelectedItem()); JOptionPane.showMessageDialog(null,"Added"); } } // if(!(e.getStateChange()== ItemEvent.SELECTED)){ // listModel.addElement(combo.getSelectedItem()); // } } public static void main(String args[]){ Jlist5 cmb = new Jlist5(); cmb.setVisible(true); } }