gpt4 book ai didi

java - 将对象添加到 JList 以在滚动 Pane 上显示时遇到问题

转载 作者:行者123 更新时间:2023-12-02 07:00:05 26 4
gpt4 key购买 nike

我一直致力于为我制作的对象创建一个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;
}
}

最佳答案

您需要将对象添加到模型而不是 jlist 面板中。添加您用于组件的内容。尝试从 jlist 获取模型并使用模型的 addElement 。

关于java - 将对象添加到 JList 以在滚动 Pane 上显示时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16766100/

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