我正在尝试从 JList 获取垂直索引。我的程序将列表中的网站、用户名和密码保存到文本文件中,如下所示:
website
username
password
当我使用 for 循环创建 usernamesAndPasswords 类的新实例时,它会这样读取:
website website website
username username username
password password password.
我认为导致问题的代码是这样的:
save.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String outFileName;
String website, username, password;
ArrayList<UsernamesAndPasswords> upInfo = new
ArrayList<UsernamesAndPasswords>();
try{
for (int i = 0; i < list1.getSize(); i++){
website = list1.getElementAt(i);
username = list1.getElementAt(i);
password = list1.getElementAt(i);
upInfo.add(new UsernamesAndPasswords(website, username, password));
}
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the file to write to: ");
outFileName = sc.nextLine();
upc.saveToTextFile(upInfo, outFileName);
} catch (Exception ex){
JOptionPane.showMessageDialog(null, "There was" +
"an error saving the file");
}
}});
如果这没有意义,请告诉我如何解决它。谢谢。
最佳答案
看看你的循环:
for (int i = 0; i < list1.getSize(); i++){
website = list1.getElementAt(i);
username = list1.getElementAt(i);
password = list1.getElementAt(i);
upInfo.add(new UsernamesAndPasswords(website, username, password));
}
当您遇到这样的索引问题时,请尝试通过替换值来使用您的大脑作为调试器:
// Loop iteration 1 (index = 0)
website = list1.getElementAt(0);
username = list1.getElementAt(0);
password = list1.getElementAt(0);
列表中的第一个元素是网站名称,但在尝试设置相应的用户名或密码之前不会增加索引。你想要:
website = list1.getElementAt(0);
username = list1.getElementAt(1);
password = list1.getElementAt(2);
根据文件的结构,您显然需要在循环中增加该索引。
website = list1.getElementAt(i);
i++;
username = list1.getElementAt(i);
i++;
password = list1.getElementAt(i);
for
循环的 i++
将负责将索引递增到元素 4,并且您必须将 getSize()
更改为将循环的退出条件设置为 getSize() - 2
以避免索引越界。
您还可以切换到将每个网站和相应数据保存在自己的行中,并根据某些分隔符(制表符、逗号等)进行分割,这可能会让您或其他人在概念上更加简单您的代码,但这种更改不仅实现起来有点微不足道,而且值(value)也微不足道。
关于java - 有没有办法用 JList 获取垂直索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56015020/