我正在尝试使用 Swing 创建一个 Java 程序。我要完成的一件事是使用 MouseListener 获取 JList 中单击项目的索引并检索与数组索引关联的变量。我的问题是,当我尝试在 MouseListener 之外调用变量时,它不会被识别。我的代码是:
public class UserListPanel extends JPanel {
LibraryController ctrl = new LibraryController();
JScrollPane scrollpane;
public int userid;
public String userName;
public UserListPanel(final Borrower[] borrowersArray) {
String userArray [] = new String [borrowersArray.length];
for (int i = 0; i < userArray.length; i++) {
userArray[i] = borrowersArray[i].getName();
}
JList userList = new JList(userArray);
scrollpane = new JScrollPane(userList);
this.add(scrollpane);
// Adds a mouse click listener to assign values from the JList to a variable on click
userList.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
JList userList = (JList)evt.getSource();
if (evt.getClickCount() >= 0) {
int index = userList.locationToIndex(evt.getPoint());
ListModel dlm = userList.getModel();
Object item = dlm.getElementAt(index);
userList.ensureIndexIsVisible(index);
userid = borrowersArray[index].getbID();
userName = borrowersArray[index].getName();
JOptionPane.showMessageDialog(null, userName);
}
}
});
}
userid = borrowersArray[index].getbID();
}
例如,在 MouseListener 构造函数中,我能够正确获取变量并将其存储在 userid 变量中,并且我的 JOptionPane 通过返回一个数字来确认这一点。但是,在构造函数之外,整数“索引”无法识别,因此如果我调用 userid,它将返回 null。我将如何在 MouseListener 之外获得索引副本?