CS3340:  Intro OOP and Design

Scrollable Selectbale Lists = using JScrollPane + JList

Here is an example of a JScrollPane displaying the contents of a JList


How do you create a Scrollable List that you can select the items in the List?

>>> truthfully there are multiple answer but, I am going to suggest JScrollPane with JList

1) USE the JList class:  to represent the data to be displayed/selected

Documentation  (https://docs.oracle.com/javase/8/docs/api/javax/swing/JList.html ) on a class called JList that lets you hold items (hint: like AddressEntry objects) that you can display---there is even some code here with a JScrollPane....then you can create an ItemListener that listens to when an item (for you an AddressEntry) is selected.

 In your listener code you might want to turn on the btnRemove.setEnabled(true) and when no item is selected do a btnRemove.setEnabled(false) [note btnRemove is the button labeled "Remove" that the user hits to remove a selected item from the list]


  • Note in the Java API documentation it says A component that displays a list of objects and allows the user to select one or more items. A separate model, ListModel, maintains the contents of the list.

STEP 1: Convert Data from collection into JList

 

use the JList constructor that uses what is called a ListModel.  
(e.g. new JList( myDefaultListModel ) ).  

 

SPECIAL NOTE:

WHY you CAN'T create JList directly from Vector of data (and must instead use constructor above that uses a ListModel

Other JList constructors let you initialize a list from a Vector or from an object that adheres to the ListModel interface. If you initialize a list with an array or vector, the constructor implicitly creates a default list model. The default list model is immutable — you cannot add, remove, or replace items in the list. To create a list whose items can be changed individually, set the list's model to an instance of a mutable list model class, such as an instance ofDefaultListModel. You can set a list's model when you create the list or by calling the setModel method. See Adding Items to and Removing Items from a List for an example.


 

STEP 2: Use JScrollPane and the JList you created to display the list data

Look at the tutorial that shows a full example (or search for one on internet) using JList and JScrollPane at  AND LOOK at example above

https://docs.oracle.com/javase/tutorial/uiswing/components/list.html



STEP 3: See here for performing event handling on a JList using ListSelectionListener at (or search for your own example on internet)--so when you select an item from ScrollPane you can do something with it

https://docs.oracle.com/javase/tutorial/uiswing/events/listselectionlistener.html

 

 

 

Example CODE

JListDisplayExample.zip << DOWNLOAD THIS CODE AND GO OVER 

PLEASE READ IT AND TRY IT OUT.  Obvioiusly it is not the exact code you will use in Project 2 as you will have created your Vector (or whatever data structure class) of AddressEntry objects (AddressBook.addressEntryList)   by reading in the data for the Database before you try to display it.   But, this code shows you how to create the JList from a ListModel, how to create the ListModel first from a Vector of AddressEntry objects and then HOW to remove an item from the JList using it's ListModel.

 

     YOUR PROJECT 2 will be different than this example code obviously
     

  • STEP A: when someone triggers event in Project 2 dealing with Loading AddressEntries from Database --> you will read in the database entries and for each one create an AddressEntry object and store in yourAddressBook.addressEntryList
  • STEP B: when you are done reading in AddresEntry object into your AddressBook.addressEntryList create from it a ListModel and add each AddressEntry object to the ListModel
  •  STEP C: Then you will create the JList using this ListModel .  

 

 

//The sample code does not retrieve from a database but, creates simply 2 AddressEntry objects to populate a Vector we use  then to //add elements to the ListModel.

.

.

.

//HERE is my main GUI Interface for the application in the zip file  WITH HIGHLIGHTS on comments 

.

.

import java.awt.EventQueue;

import javax.swing.DefaultListModel;

import javax.swing.JFrame;

import javax.swing.JList;

import javax.swing.JScrollPane;

import javax.swing.ListModel;

import javax.swing.ListSelectionModel;

import java.awt.BorderLayout;

import javax.swing.JButton;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import java.util.Vector;

public class MainWindow {

                private JFrame frame;

                Vector <AddressEntry> addressEntryList = new Vector<AddressEntry>();

                JList <AddressEntry> addressEntryJList;

                DefaultListModel<AddressEntry> myaddressEntryListModel = new DefaultListModel<AddressEntry>();

                /**

                 * Launch the application.

                 */

                public static void main(String[] args) {

                                EventQueue.invokeLater(new Runnable() {

                                                public void run() {

                                                                try {

                                                                                MainWindow window = new MainWindow();

                                                                                window.frame.setVisible(true);

                                                                } catch (Exception e) {

                                                                                e.printStackTrace();

                                                                }

                                                }

                                });

                }

                /**

                 * Create the application.

                 */

                public MainWindow() {

                                //make a dummy addressEntryList with 2 AddressEntry objects--Project 2 will read from Database instead,etc.

                                addressEntryList.add(new AddressEntry(1,"Lynne", "Grewe", "33 A street", "Hayward", "CA", 9399,"l@csueastbay.edu","555-1212"));

                                addressEntryList.add(new AddressEntry(2,"Jane", "Doe", "22 Cobble street", "Hayward", "CA", 9399,"jane@csueastbay.edu","555-9999"));

                                //because we want to REMOVE or ADD to our JList we have to create it

                                //from a DefaultListModel (see https://docs.oracle.com/javase/tutorial/uiswing/components/list.html)
                               // to which we add the elements of our collection of AddressEntry objects

                                for(int i = 0; i<addressEntryList.size(); i++)
                               
    {  this.myaddressEntryListModel.add(i, this.addressEntryList.elementAt(i)); }

                               

                               //Now when we create our JList do it from our ListModel rather than our vector of AddressEntry

                                addressEntryJList = new JList<AddressEntry>(this.myaddressEntryListModel);

                                //setting up the look of the JList

                                this.addressEntryJList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

                                this.addressEntryJList.setLayoutOrientation(JList.HORIZONTAL_WRAP);

                                this.addressEntryJList.setVisibleRowCount(-1);

                                //setup GUI and use the JList we created

                                initialize();

                }

                /**

                 * Initialize the contents of the frame.

                 */

                private void initialize() {

                                frame = new JFrame();

                                frame.setBounds(100, 100, 450, 300);

                                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                                //create scrollPane associated with JList

                                JScrollPane scrollPane = new JScrollPane(this.addressEntryJList);

                                frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

                                JButton btnRemove = new JButton("Remove");

                                btnRemove.addActionListener(new ActionListener() {  //BASED ON event from hitting remove button,
                                                                                                                            //Remove item from our JList's ListModel

                                                public void actionPerformed(ActionEvent arg0) {

                                                                int index = addressEntryJList.getSelectedIndex();

                                                                if(index != -1)//something is selected otherwise do nothing

                                                                 {   //retrieve the DeffaultListModel associated
                                                                     // with our JList and remove from it the AddressEntry at this index

                                                                    ((DefaultListModel<AddressEntry>) (addressEntryJList.getModel())).remove(index);

                                                                     // NOTE in your project 2 you will also remove it from your AddressBook.addressEntryList
                                                                    // AND ALSO remove it from the associated database table 

                                                                 }

                                                }

                                });

                                scrollPane.setColumnHeaderView(btnRemove);

                }

}



 

 



© Lynne Grewe