[英]Is there a list gui component in Java 8 Swing?
我希望列表的每个元素都有多个组件。 也许是一个标题,它下面的一些文字,甚至是一个按钮? 那可能吗? 我希望找到类似于 SwiftUI 的列表视图的东西。
像这样: https : //www.appcoda.com/wp-content/uploads/2019/06/image-8-1024x607.png (没有足够的声誉来添加图像)
它不是很详细,但Java 教程提到您可以使用自定义ListCellRenderer 。 那应该做的工作!
@ewramner 的回答是正确的。 自定义ListCellRenderer
将完成它。 这是一个使用JPanel
作为渲染组件的示例,其中包括一个嵌套的JPanel
(名为rightPanel
)。
(代码中的一些注释)
public class MultiComponentListCellRenderer {
public static void main(String[] args) {
Person mike = new Person("Mike", 25);
Person alice = new Person("Alice", 30);
DefaultListModel<Person> model = new DefaultListModel<>();
model.addElement(mike);
model.addElement(alice);
JList<Person> personJList = new JList<>(model);
personJList.setCellRenderer(new PersonListCellRenderer());
JOptionPane.showMessageDialog(null, personJList);
}
public static class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
public static class PersonListCellRenderer extends JPanel implements ListCellRenderer<Person> {
private JLabel nameLabel;
private JLabel ageLabel;
private JLabel iconLabel;
private JPanel rightPanel;
public PersonListCellRenderer() {
super(new BorderLayout());
nameLabel = new JLabel();
ageLabel = new JLabel();
iconLabel = new JLabel();
try {
Image personImg = ImageIO.read(new URL("https://cdn2.iconfinder.com/data/icons/people-80/96/Picture1-512.png"));
ImageIcon personIcon = new ImageIcon(personImg.getScaledInstance(20, 20, Image.SCALE_SMOOTH));
iconLabel.setIcon(personIcon);
} catch (IOException e) {
e.printStackTrace();
}
add(iconLabel, BorderLayout.LINE_START);
//Right panel will contain name and age, top and bottom respectively
rightPanel = new JPanel(new BorderLayout());
rightPanel.add(nameLabel, BorderLayout.PAGE_START);
rightPanel.add(ageLabel, BorderLayout.PAGE_END);
add(rightPanel, BorderLayout.CENTER);
setOpaque(true); //for visible backgrounds
rightPanel.setOpaque(true);//for visible backgrounds
}
@Override
public Component getListCellRendererComponent(JList<? extends Person> list, Person value, int index, boolean isSelected,
boolean cellHasFocus) {
nameLabel.setText(value.name);
ageLabel.setText(String.valueOf(value.age));
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
rightPanel.setBackground(list.getSelectionBackground());
rightPanel.setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
rightPanel.setBackground(list.getBackground());
rightPanel.setForeground(list.getForeground());
}
return this;
}
}
}
结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.