[英]Adding Content to a ListCellRenderer
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. 我使用ListCellRenderer创建并实现了一个Jlist,但找不到正确的方法将Item添加到列表中。
Here is the CellRenderer: 这是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. 我发现您通常通过使用listmodel来执行此操作,但是它似乎在这里不起作用,因为我必须在初始化期间将其添加到Jlist中。
JList<Product> jlist = new JList<Product>(*ListModel*);
But this isn't possible since I already have < Product > there. 但这是不可能的,因为我已经在那里有<Product>。
Thanks for taking the time looking over my obstacle. 感谢您抽出宝贵的时间查看我的障碍。
Try to create your JList
with DefaultListModel
in next way JList<Product> l = new JList<>(model = new DefaultListModel<Product>());
尝试创建自己
JList
与DefaultListModel
在接下来的方式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));
以下一种方式添加
Product
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));
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.