ListSelectionListener 运行时 JList 中出现空指针异常

发布于 2025-01-03 18:58:34 字数 3038 浏览 0 评论 0原文

我编写了一些在 JLabel 上设置图像的代码。 Image 的路径是通过 JList 上所选项目的 getSelectedValue() 方法获得的。

当用户在 JTextField(即 searchTextField)中选择任何选项后,通过在 JTextField(即 searchTextField)中键入要搜索的项目来单击搜索按钮时,将填充 Jlist。 JComboBox 中的三个项目(即 typeChooserBox)。然后我的程序从文件“Records.txt”中读取保存的记录,并分解为标记以将正确的标记(基于 typeChooserBox 的索引)与用户输入值(在 searchTextField 中)进行比较。然后它填充 JList。

下面是填充 JList 的搜索按钮的事件处理程序。

    public class searchButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
       model.clear();//This empties the JList creating nullpoint Ex
        int index=typeChooserBox.getSelectedIndex();
        String toCompare=searchTextField.getText();

        try {
                        File file = new File("Records.txt");
        BufferedReader reader = new BufferedReader(new FileReader(file));

            String line=null;
                while((line=reader.readLine())!=null){
                    String[] tokens = line.split("/");


                    if( index==0){
                        if(tokens[0].equals(toCompare))
                            model.addElement(tokens[2]);}

                    if(index==1){
                        if(tokens[1].equalsIgnoreCase(toCompare))
                            model.addElement(tokens[2]);}
                    if(index==2){
                        if(tokens[3].contains(toCompare))
                            model.addElement(tokens[2]);}
                                    }
        }
        catch(FileNotFoundException e2){
    JOptionPane.showMessageDialog(null,"File not found", "Error",JOptionPane.ERROR_MESSAGE);
    }
        catch(IOException ex){
            JOptionPane.showMessageDialog(null,"File not found", "Error",JOptionPane.ERROR_MESSAGE);
        }

}

我搜索记录时。第一次 - 我的 JList 填充了搜索结果。然后,当我从 JList 中选择一个项目时,它会起作用(在 JLabel 上设置正确的图像),直到我执行新的搜索。一旦我单击搜索按钮(第二次)。我的程序抛出 nullPointExecption 并停止工作。抱歉,我没有包含 SSCCE。但如果这些小信息还不够,请告诉我。 :)

好吧,我弄清楚了我的问题...... 单击搜索按钮时,代码 model.clear() 会清除列表中的所有项目。由于这个原因,列表中不会有任何选定的项目,从而导致空指针异常。但我该如何解决这个问题。当为 JList 调用 getSelctedValue() 时,我可以清除所有字段但避免空值吗?

我尝试这样做,但仍然没有成功。

    public class searchListListener implements ListSelectionListener {
        String s;
        String imagePath;


        public void valueChanged(ListSelectionEvent evt){ try{

         imagePath= (String) searchResult.getSelectedValue();

        ImageIcon image = new ImageIcon(imagePath);
        imageLabel.setIcon(image);
        searchResult.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);




    }
        catch(NullPointerException ne){
             JOptionPane.showMessageDialog(null, "NullPointerException");   
             model.addElement(s);
             searchResult.setSelectedValue(s, true);

            }
        finally{
            s=imagePath;
        }
}
    }




public class typeChooserBoxListener implements ItemListener{
    public void itemStateChanged(ItemEvent ev){

    }
}

我是这个java世界的新手,如果我没能帮助你,我很抱歉。:(

I wrote some code that sets the Image on the JLabel. The path of Image is obtained from getSelectedValue() method for selected item on the JList.

The Jlist was populated when user clicked search button by typing the item to be searched in JTextField(i.e searchTextField) after choosing any option out of three items in JComboBox(i.e typeChooserBox). Then my program reads saved records from a file "Records.txt" and breaks into tokens to compare proper token(based on index of typeChooserBox) with the user input value(in searchTextField). Then it populates JList.

Below is the event handler for search Button that populates JList.

    public class searchButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
       model.clear();//This empties the JList creating nullpoint Ex
        int index=typeChooserBox.getSelectedIndex();
        String toCompare=searchTextField.getText();

        try {
                        File file = new File("Records.txt");
        BufferedReader reader = new BufferedReader(new FileReader(file));

            String line=null;
                while((line=reader.readLine())!=null){
                    String[] tokens = line.split("/");


                    if( index==0){
                        if(tokens[0].equals(toCompare))
                            model.addElement(tokens[2]);}

                    if(index==1){
                        if(tokens[1].equalsIgnoreCase(toCompare))
                            model.addElement(tokens[2]);}
                    if(index==2){
                        if(tokens[3].contains(toCompare))
                            model.addElement(tokens[2]);}
                                    }
        }
        catch(FileNotFoundException e2){
    JOptionPane.showMessageDialog(null,"File not found", "Error",JOptionPane.ERROR_MESSAGE);
    }
        catch(IOException ex){
            JOptionPane.showMessageDialog(null,"File not found", "Error",JOptionPane.ERROR_MESSAGE);
        }

}

}

When I search for a record. For the First time -my JList gets populated with results of search .Then when I select an item from JList, it works(sets the correct image on JLabel) until I perform a new search. As soon as I click the search button(second time). My program throws nullPointExecption and stops working. Sorry I have not included SSCCE. But if these little information is not sufficient please let me know. :)

WELL I FIGURE OUT MY PROBLEM...
the code model.clear() clears all the item in the list when a search button is clicked. Due to this reason, there will be no selected item at the list resulting null pointer exception. But How do I solve this. Can I clear all the field but avoid null value when getSelctedValue() is called for the JList.

I tried doing this but it still didn't work.

    public class searchListListener implements ListSelectionListener {
        String s;
        String imagePath;


        public void valueChanged(ListSelectionEvent evt){ try{

         imagePath= (String) searchResult.getSelectedValue();

        ImageIcon image = new ImageIcon(imagePath);
        imageLabel.setIcon(image);
        searchResult.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);




    }
        catch(NullPointerException ne){
             JOptionPane.showMessageDialog(null, "NullPointerException");   
             model.addElement(s);
             searchResult.setSelectedValue(s, true);

            }
        finally{
            s=imagePath;
        }
}
    }




public class typeChooserBoxListener implements ItemListener{
    public void itemStateChanged(ItemEvent ev){

    }
}

I am new on this java world, Sorry if I have not been able to help you to help me.:(

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

话少心凉 2025-01-10 18:58:34

如果没有异常的堆栈跟踪或 searchResult.getSelectedValue() 中发生的情况,很难判断。

也许试试这个:

public void valueChanged(ListSelectionEvent evt){
    if( evt.getValueIsAdjusting() ) return;

    // your code here

}

It is hard to tell without the stack trace of your exception or what happens in searchResult.getSelectedValue().

Perhaps try this:

public void valueChanged(ListSelectionEvent evt){
    if( evt.getValueIsAdjusting() ) return;

    // your code here

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文