我有一个JList
由 a 支持DefaultListModel
并有一个自定义的CellRenderer
.
CellRenderer
用于JCheckBox
在我的JList
.
当我尝试修改中某个元素的选中状态时,DefaultListModel
它似乎不会更新我的JList
. 当我尝试使用三种方法中的任何一种来获取某个索引处的元素时,就会发生这种情况DefaultListModel.elementAt(...)
:DefaultListModel.get(...)
或DefaultListModel.getElementAt(...)
.
为什么我JList
没有收到更新?
JList
我的部分中下面被注释掉的代码部分将起作用。但是,我不喜欢仅仅为了更改布尔值而将新对象复制到该位置。
这是我的代码,为了便于阅读和理解而进行了简化。
JList
部分
public AppsPanel() {
super(new BorderLayout());
this.appsListModel = new DefaultListModel<AppListItem>();
this.appsList = new JList<AppListItem>(this.appsListModel);
this.appsList.setCellRenderer(new AppsListRenderer());
this.appsList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JList list = (JList) e.getSource();
int index = list.locationToIndex(e.getPoint());
AppListItem appListItem = (AppListItem)list.getModel().getElementAt(index);
appListItem.setSelected(!appListItem.isSelected());
list.repaint(list.getCellBounds(index, index));
}
});
this.appsScrollPane = new JScrollPane(this.appsList);
this.add(this.appsScrollPane);
}
...
public void selectAllApps() {
// for (int i = 0; i < this.appsListModel.size(); i++) {
// this.appsListModel.set(i, new AppListItem(this.appsListModel.get(i).getApp(), true));
// }
for (int i = 0; i < this.appsListModel.size(); i++) {
this.appsListModel.getElementAt(i).setSelected(true);
}
}
CellRenderer
部分。
public class AppsListRenderer extends JCheckBox implements ListCellRenderer<AppListItem> {
@Override
public Component getListCellRendererComponent(JList<? extends AppListItem> list, AppListItem value, int index, boolean isSelected, boolean cellHasFocus) {
this.setSelected(value.isSelected());
if (value.getApp() != null) {
this.setText(value.getApp().getAppName());
}
return this;
}
}
AppListItem
波乔
public class AppListItem {
private App app;
private boolean selected;
public AppListItem(App app, boolean selected) {
this.app = app;
this.selected = selected;
}
public App getApp() {
return app;
}
public void setApp(App app) {
this.app = app;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
App
波乔
public class App {
private String appName;
private String appPath;
public App(String appName, String appPath) {
this.appName = appName;
this.appPath = appPath;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getAppPath() {
return this.appPath;
}
public void setAppPath(String appPath) {
this.appPath = appPath;
}
}