0

I'm doing an assignment where I'm making a program that generates 20 random numbers and puts them in an arraylist, a hashset and a treeset. It is supposed to show those numbers in JList1. Then, I am going to use HashSet to display unique numbers only, and TreeSet to display the numbers sorted. I made three JLists, and made one function for each of them to update the GUI (there's probably an easier way to do this, but thats all I could come up with due to me being quite new to java). So, for example my updateGUI function used to display the arraylist in my JList looks like this:

public void updateGUI(JList someList, ArrayList<Integer> anyarraylist){
        DefaultListModel m = new DefaultListModel();
        for (Object  s : anyarraylist) {
            m.addElement(s);
        }
        someList.setModel(m);
    }

I then call that function when I press a button by using ActionEvent:

@Override
public void actionPerformed(ActionEvent arg0) {

    generateNumbers();

    this.updateGUI(this.numbers1, numberlist);

Where generateNumbers is my function to generate 20 random numbers, numbers1 is my first JList and numberlist is the name of my arraylist.

I did pretty much the exact same thing for HashSet to display a JList with unique numbers, and it worked. However, I then tried to do the same for TreeSet, which gave me a "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException"-error. The function looks like this:

    public void oppdaterGUI3(JList someList, TreeSet<Integer> anysortedlist){
    DefaultListModel m = new DefaultListModel();
    for (Object  s : anysortedlist) {
        m.addElement(s);
    }
    someList.setModel(m);
}

Why doesn't this work? I thought TreeSet would work the same way as HashSet. Any help is appreciated. I can post the full error and code if necessary.

Thank you.

4

1 回答 1

1

尽管缺乏信息,但我将以下内容制定为答案。

查看 NullPointerException 的堆栈跟踪。它给出了它发生的行号。

TreeSet 可能被定义了两次,一次是作为局部变量。或者有一种情况,树集的副本也必须发生。类似的东西。

您可以使用断点对其进行调试。遍历树集 var 和另一个 var 的所有用法。

对于响应更快的 GUI,请使用以下模式。

@Override
public void actionPerformed(ActionEvent arg0) {
    EventQueue.invokeLater(new Runnable()) {
        @Override
        public void run() {
            generateNumbers();
            /*MyClass.this.*/ updateGUI(this.numbers1, numberlist);
        }
    });
}
于 2013-02-26T13:39:02.833 回答