Java 有没有办法用JList获取垂直索引?

Java 有没有办法用JList获取垂直索引?,java,jlist,Java,Jlist,我试图从JList中获取垂直索引。我的程序在列表中将网站、用户名和密码保存到如下文本文件: website username password website website website username username username password password password. 当我使用for循环创建usernamesAndPasswords类的新实例时,它的内容如下: website username password website website websit

我试图从JList中获取垂直索引。我的程序在列表中将网站、用户名和密码保存到如下文本文件:

website
username
password
website website website
username username username
password password password. 
当我使用for循环创建usernamesAndPasswords类的新实例时,它的内容如下:

website
username
password
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");
            }
        }});
save.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
字符串输出名;
字符串网站、用户名、密码;
ArrayList upInfo=new
ArrayList();
试一试{
对于(int i=0;i
如果这不合理,请告诉我如何修复它。谢谢。

看看你的循环:

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));
}
列表中的第一个元素是网站名称,但在尝试设置相应的用户名或密码之前,不会增加索引。你想要:

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
,以避免索引超出范围


您还可以切换到将列表与每个网站和相应的数据一起保存在自己的行中,并根据一些分隔符(制表符、逗号等)进行拆分,这可能会使您或其他人在查看代码时在概念上更加简单,但这种更改不仅实现起来有点琐碎,但在价值上也有些微不足道。

我也尝试过使用list1.getElementAt(I)list1.getElementAt(I+1)和list.getElementAt(I+2),这会由于索引超出范围而导致错误。如果答案有帮助,请继续并单击答案左侧的复选标记,以便遇到此问题的其他用户知道什么对您有效。