简体   繁体   English

如果Jlist中未选择任何内容

[英]If nothing is selected in Jlist

I´m writing a program where different symbols are drawn on an image based on what the user selects in a JList. 我正在编写一个程序,其中根据用户在JList中选择的内容在图像上绘制不同的符号。 This works fine, but my problem is that I want to place a symbol on the image if nothing is selected in the JList as well. 这可以正常工作,但是我的问题是,如果JList中也未选择任何内容,我想在图像上放置符号。 Is there some way to check if the selection is empty? 有什么方法可以检查选择是否为空? This is my code right now, and it throws me a NullPointerException if I don´t select anything from the JList. 这是我现在的代码,如果我没有从JList中选择任何内容,它将抛出NullPointerException。

if(categoriesList.getSelectedValue().equals("Bus")) {
            BusSymbol bs = new BusSymbol(x, y);
            mp.add(bs);
        } 
        else if 
(categoriesList.getSelectedValue().equals("Underground")) {
            UndergroundSymbol us = new UndergroundSymbol(x,y);
            mp.add(us);
        }
        else if (categoriesList.getSelectedValue().equals("Train")) {
            TrainSymbol ts = new TrainSymbol(x,y);
            mp.add(ts);
        }
        else if (categoriesList.getSelectedValue().equals(null)) {

            NoCategorySymbol ncs = new NoCategorySymbol(x,y);
            mp.add(ncs);
        }

        mp.validate();
        mp.repaint();

You can't check for a null value using .equals you need to use == . 您不能使用需要使用== .equals检查空值。

categoriesList.getSelectedValue() == null

This is because .equals calls a method on the object. 这是因为.equals在对象上调用方法。 If the object is null you can't do that. 如果对象为null,则不能这样做。

You should use JList.isSelectionEmpty() as a condition instead of testing against the value that might be null . 您应该使用JList.isSelectionEmpty()作为条件,而不是针对可能为null的值进行测试。

You should either make this test first, and/or change all the other tests which have this unfortunate syntax : 您应该先进行此测试,和/或更改所有其他使用此不幸语法的测试:

mightBeNull.equals(neverNull)

As a general rule it is generally better to avoid this syntax and use neverNull.equals(mightBeNull) instead, as it avoids attempting to invoke the inexistant null.equals() method. 通常,最好避免使用这种语法,而改用neverNull.equals(mightBeNull) ,因为这样可以避免尝试调用不存在的null.equals()方法。

I propose the following code : 我提出以下代码:

if (categoriesList.isSelectionEmpty()) {
    mp.add(new NoCategorySymbol(x,y));
} else {
    // here we know categoriesList.getSelectedValue() isn't null
    String selectedValue = categoriesList.getSelectedValue());
    if ("Underground".equals(selectedValue)) {
       mp.add(new UndergroundSymbol(x,y));
    } else if ("Train".equals(selectedValue)) {
       mp.add(new TrainSymbol(x, y));
    }
}
mp.validate();
mp.repaint();
public boolean isElementSelected(){ return categoriesList.getSelectedValue() == null;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM