Solved

JList -> Won't display my listmodel

Posted on 2010-08-15
2
731 Views
Last Modified: 2013-12-14
Right, I am sure I am doing something wrong, but I can't find it.

All I am trying to do, at this point, is set the model to something I create. I can't even clear the standard model...

Any ideas?
-Ryan
public class SearchList extends JList{

     public SearchList() {
        super();
        this.setModel(new DefaultListModel());
        //this.repaint();
        //items.add("Test");
        //items.add("Another Test");
        //items.add("Yet another test.");
        
        //BuildPrototypeCells();
        //setCellRenderer(new PolyRenderer());
        //RefreshModel();
    }

     private void RefreshModel() {
        DefaultListModel newModel = new DefaultListModel();
        
        for(int i = 0; i < items.size(); i++) {
                newModel.addElement(new SearchItem((String)(items.get(i))));
        }

        this.setModel(newModel);
        this.validate();
        //this.repaint();
    }

     // I love ArrayLists. Type declarations are for the weak.
     private ArrayList items = new ArrayList();


     public void SetItems(ArrayList items) {
         this.items = items;
     }

     public ArrayList GetItems() {
         return items;
     }

    private ImageIcon defaultIcon = new ImageIcon ("defaultIcon.png");
    private JComponent resultCellPrototype;
    private JLabel fileNameLabel, textNameLabel, directoryNameLabel, imageNameLabel, fileSizeLabel, textSizeLabel, textWordCountLabel,directoryCountLabel,imageSizeLabel, imageIconLabel;

     

    private void BuildPrototypeCells() {
        resultCellPrototype = new JPanel();
        resultCellPrototype.setLayout (new GridBagLayout());
        AddWithGridBag(new JLabel(defaultIcon), resultCellPrototype, 0, 0, 1, 2, GridBagConstraints.WEST, GridBagConstraints.BOTH, 0, 0);
        fileNameLabel = new JLabel();
        Font defaultLabelFont = fileNameLabel.getFont();
        Font nameFont = defaultLabelFont.deriveFont(Font.BOLD,defaultLabelFont.getSize()+2);
        fileNameLabel.setFont(nameFont);
        AddWithGridBag(fileNameLabel, resultCellPrototype, 1, 0, 1, 1, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, 1, 0);
        fileSizeLabel = new JLabel();
        AddWithGridBag(fileSizeLabel, resultCellPrototype, 1, 1, 1, 1, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, 1, 0);
        Opacify(resultCellPrototype);

    }


     private void AddWithGridBag(Component comp, Container cont, int x, int y, int width, int height, int anchor, int fill, int weightx, int weighty) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = width;
        gbc.gridheight = height;
        gbc.anchor = anchor;
        gbc.fill = fill;
        gbc.weightx = weightx;
        gbc.weighty = weighty;
        cont.add(comp, gbc);
    }

    private void Opacify(Container prototype) {
        Component[] comps = prototype.getComponents();
        for (int i=0; i<comps.length; i++) {
            if (comps[i] instanceof JComponent)
                ((JComponent)comps[i]).setOpaque(true);
        }
    }

    class SearchItem extends Object {
        String file;
        public SearchItem (String f) {
            file = f;
        }
    }



        class PolyRenderer extends Object implements ListCellRenderer {
            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {

                if(value instanceof SearchItem){
                    SearchItem item = (SearchItem)(value);
                    fileNameLabel.setText(item.file);
                    //fileSizeLabel.setText(item.file.length() + " bytes");
                    setColorsForSelectionState(resultCellPrototype, isSelected);
                    return resultCellPrototype;
                }
                else {
                    return resultCellPrototype;
                }
            }
            
            private void setColorsForSelectionState (Container prototype, boolean isSelected) {
                Component[] comps = prototype.getComponents();
                for (int i = 0;  i <comps.length; i++) {
                    if (isSelected) {
                        comps[i].setForeground(UIManager.getLookAndFeel().getDefaults().getColor("List.selectionForeground"));
                        comps[i].setBackground(UIManager.getLookAndFeel().getDefaults().getColor("List.selectionBackground"));
                    } else {
                        comps[i].setForeground(UIManager.getLookAndFeel().getDefaults().getColor("List.foreground"));
                        comps[i].setBackground(UIManager.getLookAndFeel().getDefaults().getColor("List.background"));
                    }
                }
            }
    }
}

Open in new window

0
Comment
Question by:rossryan
2 Comments
 

Author Comment

by:rossryan
Comment Utility
I hate Java with a passion. Why must everything be like a trip across a old, rickety wooden bridge over a pit filled with lava, with Kwejfdwijefioj the Unthinkable blocking your way?

-Ryan
0
 
LVL 1

Accepted Solution

by:
cusl-info earned 500 total points
Comment Utility
Hi...

What a mess... Just cleaning :

First, don't extend JList. This is not necessary.

Second, define your model in another class. So it can be reused.

  class MyModel extends DefaultListModel {

    private ArrayList<SearchItem> items = new ArrayList<SearchItem>();

    public void addItem(SearchItem item) {
      items.add(item);
      fireContentsChanged(this, 0, items.size());
    }

    public Object getElementAt(int index) {
      return items.get(index);
    }

    public int getSize() {
      return items.size();
    }

  }

Then, here is how to use it :

   JList list = new JList();
    MyModel model = new MyModel();
    list.setModel(model);
    list.setCellRenderer(new PolyRenderer());
    model.addItem(new SearchItem("Test"));
    model.addItem(new SearchItem("Test1"));
    model.addItem(new SearchItem("Test2"));
    model.addItem(new SearchItem("Test3"));

If you want to test it, add it to a frame :

    JFrame frame = new JFrame();
    frame.getContentPane().add(new JScrollPane(list));
    frame.setVisible(true);
    frame.pack();

Third, you also can group all the methods related to the renderer in a separate class : AddWithGridBag, Opacify, setColorsForSelectionState.

Hope that helps

Michel
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now