我一直在为我制作的对象创建一个 defaultlistcellrender,但到目前为止,将对象添加到 JList 非常困难。我附上了任何建议的代码。谢谢!
public class JTabbedPaneTester extends JFrame
{
private List<Human> members = new ArrayList<Human>();
private JList newbie = new JList();
private DefaultListModel model = new DefaultListModel();
public JTabbedPaneTester() throws FileNotFoundException
{
super("JTabbedPane Demo");
JTabbedPane tabbedPane = new JTabbedPane();
JPanel gladiator = new JPanel();
getContentPane().add(gladiator);
tabbedPane.addTab("Gladiator", null, Gladiator, "");
Box listOfPlayers = Box.createVerticalBox();
listOfPlayers.add(Box.createRigidArea(new Dimension(100,100)));
listOfPlayers.setBorder(new TitledBorder("List of Players"));
JScrollPane playerViewer = new JScrollPane();
playerViewer.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
listOfPlayers.add(playerViewer);
JButton AddIndividual = new JButton("Add a Player");
listOfPlayers.add(addIndividual);
gladiator.add(listOfPlayers);
final HumanListModel modelx = new HumanListModel();
final JTable newbiex = new JTable(modelx);
newbiex.setDefaultRenderer(Human.class, new HumanRenderer());
playerViewer.setViewportView(newbiex);
addIndividual.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Human temp;
try {
temp = new Human();
modelx.addHuman(temp);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
});
add(tabbedPane);
}
}
这是这里有人很好地帮助我的渲染器
class HumanRenderer extends DefaultListCellRenderer
{
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus)
{
JLabel label = new JLabel();
if (value != null)
{
Human human = (Human) value;
label.setText(human.getSurname() + ", " + human.getFirstName());
}
return label;
}
}