Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

JList -> Won't display my listmodel

Posted on 2010-08-15
2
Medium Priority
?
744 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
ID: 33441808
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 2000 total points
ID: 33452908
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

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.
Suggested Courses

782 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