gpt4 book ai didi

java - 将 ListCellRenderer 应用于 JList 上的各个单元格

转载 作者:行者123 更新时间:2023-12-01 08:13:27 26 4
gpt4 key购买 nike

是否可以将 listcellrenderer 应用于 jlist 中的一个单元格?我的代码目前在应用渲染器方面工作正常,但我想为每个条目设置不同的动态变量。如果这有点含糊,我们深表歉意..

总结一下 - 我想将 listcellrenderer 应用于列表中的一个单元格,我该怎么做?

最佳答案

您必须将 ListCellRenderer 应用于列表中的所有元素,但这并不意味着它必须以相同的方式渲染所有元素。例如,您可以根据单元格的值(原始值,甚至仅基于值的类,甚至基于单元格的索引)来呈现单元格:

package com.example;

import java.awt.Color;
import java.awt.Component;

import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;

public class ListCellRendererExample extends JFrame {

public ListCellRendererExample() {
DefaultListModel model = new DefaultListModel();
model.addElement(Color.BLUE);
model.addElement("hello");
model.addElement(5);
model.addElement(Color.RED);

JList jlist = new JList(model);
jlist.setCellRenderer(new SuperDuperListCellRenderer());
add(new JScrollPane(jlist));

setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationByPlatform(true);
setVisible(true);
}

/**
* @param args
*/
public static void main(String[] args) {
new ListCellRendererExample();
}

private static class SuperDuperListCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {

// If the value is a color, give the cell a blank value but save its
// value so we can later change its background to the value's color.
Color bgColor = null;
if (value instanceof Color) {
bgColor = (Color) value;
value = " ";
}

// Prepend the index to the "even" rows (the first row is row 1)
if ((index + 1) % 2 == 0) {
value = index + ": " + value;
}

Component renderComponent = super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);

// If the value is a color, set the cell's background to that color.
if (bgColor != null) {
renderComponent.setBackground(bgColor);
}

return renderComponent;
}
}
}

关于java - 将 ListCellRenderer 应用于 JList 上的各个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15488883/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com