我正嘗試使用Swing創建Java程序。我試圖完成的一件事是使用MouseListener獲取JList中單擊項目的索引,並檢索與數組索引關聯的變量。我的問題是,當我嘗試調用MouseListener之外的變量時,它不會被識別。我的代碼之中:變量不能在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構造我能得到正確的變量並將其存儲在用戶標識變量內,例如,我的JOptionPane通過返回數量證實了這一點。在構造函數之外的Hoewever中,整數「index」未被識別,因此如果我要調用userid,它將返回null。我會如何去尋找MouseListener之外的索引副本?
你是對的,謝謝! –
@JasonWu隨時歡迎! – Abubakkar
實際上,沒有,經過進一步檢查,它不起作用。該變量從來沒有從MouseListener構造函數獲取值,並且默認爲0.例如,當我調用用戶名時,它總是返回與列表的第一個索引(0)關聯的名稱。顯然,構造函數外部的索引永遠不會傳入內部的整數。 –