Link to home
Start Free TrialLog in
Avatar of mwalker
mwalkerFlag for United States of America

asked on

Question on creating a custom DefaultListModel

I'd like to be able to display a 2D array within a JList.  The array will look like this:

private final String[][] selection =
     { {"value1","display string 1" }, {"value2","display string 2"} ... };

where the goal I'm trying to achieve is to view "the display strings" within the JList.

The first thing I did was to create this class that extends javax.swing.DefaultListModel:

public class ValueListModel extends DefaultListModel {
     private String[][] values;
     
     public ValueListModel(String[][] values) {
          this.values = values;
     }
      
     public Object getElementAt(int index) {
          return values[index][1];
     }
}

Next, I create a custom ListCellRenderer as:

public class ValueListCellRenderer extends JLabel implements ListCellRenderer {
     private String[][] values;
      
     public ValueListCellRenderer(String[][] values) {
          setOpaque(true);
          this.values = values;
     }

     public Component getListCellRendererComponent(JList list, Object value,
                  int index, boolean isSelected, boolean cellHasFocus) {
          setText(values[index][1]);
          setBackground(isSelected ? UIManager.getColor("List.selectionBackground")
                  : UIManager.getColor("List.background"));
          setForeground(isSelected ? UIManager.getColor("List.selectionForeground")
                  : UIManager.getColor("List.foreground"));
          return this;
     }
}

Finally in my GUI code, I instantiate instances of these classes and set the JList's model and cell renderer with the respective instances.  My problem is that the display strings are not being displayed.

Question: Will I have to override more of the methods of the DefaultListModel? If so, which ones?

Thanks in advance for any assistance.
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
8-)