我有以下代码:
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
public class fenetre extends JFrame {
private JList list1, list2;
// private static String[] players1 = {"Player 1", "Player 2"};
// private static String[] players2 = {"Player 3", "Player 4"};
private JLabel label;
private JPanel panel;
private DefaultListModel model1, model2;
@SuppressWarnings("unchecked")
public fenetre(List<character> eq1,List<character> eq2) {
super("JList Example");
setLayout(new BorderLayout());
model1 = new DefaultListModel();
for (int i = 0; i < eq1.size(); i++) {
model1.addElement(eq1.get(i));
}
List<character> lis = new ArrayList<>();
list1 = new JList<String>(model1);
list1.setVisibleRowCount(2);
list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(new JScrollPane(list1), BorderLayout.WEST);
model2 = new DefaultListModel();
for (int i = 0; i < eq2.size(); i++) {
model2.addElement(eq2.get(i));
}
list2 = new JList(model2);
list2.setVisibleRowCount(2);
list2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(new JScrollPane(list2), BorderLayout.EAST);
panel = new JPanel();
panel.setBackground(Color.WHITE);
add(panel, BorderLayout.SOUTH);
label = new JLabel();
panel.add(label);
list1.addListSelectionListener(event -> {
int index = list1.getSelectedIndex();
if (index != -1) {
// Update the label with the selected player's name
label.setText("Selected player: " + model1.get(index).getName());
}
});
list2.addListSelectionListener(event -> {
int index = list2.getSelectedIndex();
if (index != -1) {
// Update the label with the selected player's name
label.setText("Selected player: " + model2.get(index));
}
});
}
}
在本节中:
list1.addListSelectionListener(event -> {
int index = list1.getSelectedIndex();
if (index != -1) {
// Update the label with the selected player's name
label.setText("Selected player: " + model1.get(index).toString());
}
});
我想把model1.get(index).toString()替换为model1.get(index).getName()
model1如果填充了“character“类型的对象,如您所见,我创建了此类型并实现了方法getName,但我无法调用它,因为不清楚model1.get(index)是否为character类型。
我能做些什么来让它工作呢?
我不清楚我可以尝试什么来解决这个问题
1条答案
按热度按时间e0bqpujr1#
你将陷入非常深的深渊
ListModel
应该包含Character
的示例,然后您应该使用ListCellRenderer
API来定制呈现值的方式。然后,您应该使用通用约束来限制
ListModel
和JList
,使其仅接受Character
的示例首先看一下How to Use Lists,然后编写一个自定义单元格呈现器和Generics
要向
JList
和DefaultListModel
添加通用支持,只需执行以下操作...当您创建
JList
时,您可以执行以下操作...然后当你想从模型中得到一个
Character
时,你可以简单地做...