Question

I created and implemented a Jlist with a ListCellRenderer, but I am not able to find the right way to add an Item to the list.

Here is the CellRenderer:

public class ListProductRenderer implements ListCellRenderer<Product> {
public Component getListCellRendererComponent(
        JList<? extends Product> list, Product value, int index,
        boolean isSelected, boolean cellHasFocus) {

    String namex = value.getName();
    Box box = Box.createVerticalBox();
    JLabel l = new JLabel(namex);
    JLabel p = new JLabel("Price:" + value.getPrice());
    JLabel q = new JLabel("Quantity:" + value.getQuantity());
    Font f = l.getFont();
    f = f.deriveFont(Font.ITALIC, f.getSize() * 0.8f);
    p.setFont(f);
    q.setFont(f);
    box.add(l);
    box.add(p);
    box.add(q);
    if (isSelected) {
        box.setBorder(BorderFactory.createLineBorder(Color.blue));
    }
    return box;
}
}

And here is the implementation in the view:

JList<Product> jlist = new JList<Product>();
jlist.setCellRenderer(new ListProductRenderer());
JScrollPane scrollPane = new JScrollPane(jlist);
LeftPanel.add(scrollPane, BorderLayout.CENTER);

Product is an own class and I want to add this example:

Product Auto = new Product("Auto", 10, 3500.50);

What I found is that you do this normally by using a listmodel but it doesn't seem to work here since I would have to add it to the Jlist during initialition like this.

JList<Product> jlist = new JList<Product>(*ListModel*);

But this isn't possible since I already have < Product > there.

Thanks for taking the time looking over my obstacle.

Was it helpful?

Solution

Try to create your JList with DefaultListModel in next way JList<Product> l = new JList<>(model = new DefaultListModel<Product>()); , here model it's model for your list.

Add your Product in next way model.addElement(new Product("Auto", 10, 3500.50)); or if you want to add it by button action, next button can do that:

    JButton btn = new JButton("add");
    btn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            model.addElement(new Product("Auto", 10, 3500.50));
        }
    });

read tutorial for using Lists

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top