JList with a DefaultListModel||Java Codes
DefaultListModel is a ListModel implementation that extends from AbstractListModel class.Below program is example of how you can implement DefaultListModel in a JList
JList with a DefaultListMode Example
[
import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JList; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JScrollPane; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; public class DefaultListModelExample extends JPanel{ public JList list; public JButton addB,removeB; public static JFrame f; public DefaultListModel m; DefaultListModelExample() { m=new DefaultListModel(); list=new JList(m); JScrollPane pane = new JScrollPane(list); add(pane); addB=new JButton("Add"); addB.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { String s=JOptionPane.showInputDialog(null, "Enter your favourite programming language", "",JOptionPane.INFORMATION_MESSAGE); m.add(0,s); } }); add(addB); removeB=new JButton("Remove"); removeB.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event ) { m.removeElementAt(0); } }); add(pane, BorderLayout.NORTH); add(addB, BorderLayout.WEST); add(removeB, BorderLayout.EAST); } public static void main(String args[]) { f=new JFrame(" DefaultListModelExample "); f.setContentPane(new DefaultListModelExample ()); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(300,230); f.setLocationRelativeTo(null); f.setVisible(true); } }
]
Code Explanation
Above class extends JPanel.Code [ f.setContentPane(new DefaultListModelExample ());] gets all JPanel contents and displays them.
The class has two JButtons.One button addElement to DefaultListModel while the other JButton removeElementAt index 0.
Code to addElement at Index 0 is [addB.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent event) { String s=JOptionPane.showInputDialog(null, "Enter your favourite programming language", "",JOptionPane.INFORMATION_MESSAGE); m.add(0,s); }
});]
[JOptionPane.showInputDialog]-gets the string to be added to DefaultListModel.
Code to remove Element at index 0 is [removeB.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent event ) { m.removeElementAt(0); } });
}]
[setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);]-closes JFrame and exits application when close button is clicked.
[ add(pane, BorderLayout.NORTH);
add(addB, BorderLayout.WEST);
add(removeB, BorderLayout.EAST);]-this is the code that setLayout of components in JPanel.