package examples; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; /** * CS401 Example 37b * * Demonstrates the use of the Model/View/Controller implementation of the JList * component. * * @author PJ Dillon */ public class ex37b implements ActionListener, ListSelectionListener { private DefaultListModel from, to; private JList fromList, toList; private Container c; public ex37b() { JFrame window = new JFrame("Example 37b"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); c = window.getContentPane(); c.setLayout(new FlowLayout()); from = new DefaultListModel(); from.addElement(new MyColor("Black", Color.black)); from.addElement(new MyColor("Blue", Color.blue)); from.addElement(new MyColor("Red", Color.red)); from.addElement(new MyColor("Orange", Color.orange)); from.addElement(new MyColor("Green", Color.green)); from.addElement(new MyColor("Cyan", Color.cyan)); from.addElement(new MyColor("Gray", Color.gray)); from.addElement(new MyColor("Magenta", Color.magenta)); from.addElement(new MyColor("Green", Color.green)); from.addElement(new MyColor("White", Color.white)); from.addElement(new MyColor("Yellow", Color.yellow)); fromList = new JList(from); fromList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); c.add(new JScrollPane(fromList)); JButton select = new JButton("Select >>>"); select.addActionListener(this); c.add(select); to = new DefaultListModel(); toList = new JList(to); toList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); toList.addListSelectionListener(this); c.add(new JScrollPane(toList)); window.setSize(520, 200); window.setVisible(true); } public void actionPerformed(ActionEvent e) { Object[] values = fromList.getSelectedValues(); for(Object o : values) if(!to.contains(o)) to.addElement(o); } public void valueChanged(ListSelectionEvent e) { c.setBackground(((MyColor)to.get(toList.getSelectedIndex())).getColor()); } public static void main(String[] args) { new ex37b(); } private class MyColor { private Color color; private String name; public MyColor(String n, Color c) { color = c; name = n; } public String toString() {return name;} public Color getColor() {return color;} } }