我有以下问题: 我的框架中有2个JLists:
listModel = new DefaultListModel();
ownlistModel = new DefaultListModel();
fillList();
ownBookList = new JList(ownlistModel);
ownBookList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ownBookList.setLayoutOrientation(JList.VERTICAL);
ownBookList.setSelectedIndex(-1);
userlist = new JList(listModel);
userlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
userlist.setLayoutOrientation(JList.VERTICAL);
userlist.setSelectedIndex(0);
现在,这些是互斥的,所以如果有人点击一个列表中的项目,则应清除另一个列表中的先前选择。
ls2Handler = new ListSelectionListener(){
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
// System.out.println(ownBookList.getSelectedValue().toString().length());
Global.selectedUser = ownBookList.getSelectedValue().toString();
Global.selectedIndex = ownBookList.getSelectedIndex();
userlist.clearSelection();
updateFields(Global.selectedUser, 1);
}
}
};
lsHandler = new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
// System.out.println(userlist.getSelectedValue().toString().length());
Global.selectedUser = userlist.getSelectedValue().toString();
Global.selectedIndex = userlist.getSelectedIndex();
ownBookList.clearSelection();
updateFields(Global.selectedUser, 0);
}
}
};
userlist.addListSelectionListener(lsHandler);
ownBookList.addListSelectionListener(ls2Handler);
在调用Value is adjustment函数时,我总是得到nullpointerException:
线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException 在图书$ 3.valueChanged(Books.java:199)at javax.swing.JList.fireSelectionValueChanged(未知来源)
为什么?如您所见,它们已被声明并且应该可以访问。
答案 0 :(得分:4)
getSelectedValue()
方法可以返回null
,并且您在toString()
个对象上调用null
userlist.getSelectedValue().toString();
请参阅该方法的文档:
返回最小的选定单元格索引的值;在列表中仅选择单个项目时所选的值。选择多个项目时,它只是最小选定索引的值。如果没有选择,则返回null。
当您在列表B
上选择内容时清除列表A
上的选择,您将很快遇到此异常。
答案 1 :(得分:3)
感谢Robin我明白了。我不知道方法clearselection()会触发侦听器。 它既快又脏,但它有效:
ls2Handler = new ListSelectionListener(){
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
if (ownBookList.getSelectedValue()!=null) {
userlist.clearSelection();
Global.selectedUser = ownBookList.getSelectedValue().toString();
Global.selectedIndex = ownBookList.getSelectedIndex();
updateFields(Global.selectedUser);
}
else {
}
}
}
};
lsHandler = new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
if (userlist.getSelectedValue()!=null) {
ownBookList.clearSelection();
Global.selectedUser = userlist.getSelectedValue().toString();
Global.selectedIndex = userlist.getSelectedIndex();
updateFields(Global.selectedUser);
}
else {
}
}
}
};
再次感谢!