JList
JList object shows a list of objects, it allows to add or remove objects from the list.
import javax.swing.*; import java.awt.event.*; public class ListExample2 { ListExample2(){ JFrame f= new JFrame(); final JLabel label = new JLabel(); label.setSize(500,100); JButton b=new JButton("Show"); b.setBounds(200,150,80,30); final DefaultListModell1 = new DefaultListModel<>(); l1.addElement("Honda"); l1.addElement("Yamaha"); l1.addElement("Suzuki"); l1.addElement("Ducati"); final JList list1 = new JList<>(l1); list1.setBounds(100,100, 75,75); DefaultListModel l2 = new DefaultListModel<>(); l2.addElement("150cc"); l2.addElement("250cc"); l2.addElement("699cc"); l2.addElement("900cc"); final JList list2 = new JList<>(l2); list2.setBounds(100,200, 75,75); f.add(list1); f.add(list2); f.add(b); f.add(label); f.setSize(450,450); f.setTitle("JList - demo "); f.setLayout(null); f.setLocationRelativeTo(null); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String data = ""; if (list1.getSelectedIndex() != -1) { data = "Motorbike Brand Selected: " + list1.getSelectedValue(); label.setText(data); } if(list2.getSelectedIndex() != -1){ data += ", Engine Capacity Selected: "+list2.getSelectedValue(); ; label.setText(data); } } }); } public static void main(String args[]) { new ListExample2(); } }
Following program uses DefaultListModel to store objects. In the program how to add new objects and remove object from list is shown.
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ListExample { ListExample(){ JFrame f= new JFrame(); JButton rbtn = new JButton("Removal"); JButton abtn = new JButton("Addelement"); JTextField tword = new JTextField(10); DefaultListModell1 = new DefaultListModel<>(); l1.addElement("One"); l1.addElement("Two"); l1.addElement("Three"); l1.addElement("Four"); JList list = new JList (l1); list.setBounds(10,10, 75,125); tword.setBounds(210,110,100,20); rbtn.setBounds(100,140,100,20); abtn.setBounds(210,140,100,20); f.add(list); f.add(rbtn); f.add(abtn); f.add(tword); f.setSize(400,400); f.setLayout(null); f.setTitle("JList - Demo"); f.setLocationRelativeTo(null); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); rbtn.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ l1.remove(0); } }); abtn.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(tword.getText().length()>0){ l1.addElement(tword.getText()); } } }); } public static void main(String args[]) { new ListExample(); } }