How do I write my own ListSelectionEvent?

261 Views Asked by At

I made a GUI that holds a list. When a selection is made in that list, via the user clicking the list selection, some action is performed. I want to be able to test that action without having to actually make a selection through the GUI. For example I have my GUI.java and a separate GUITest.java. Id like to do something likeGUITest.java

valueChanged() is a method from the java interface ListSelectionListener and only accepts parameters of type ListSelectionEvent. So ultimately, how would I create my own ListSelectionEvent variable that holds the action that "a" was selected?

1

There are 1 best solutions below

0
Alder Moreno On

I just thought of this which performs the same task much easier I think. The method valueChanged(ListSelectionEvent e) automatically runs when a selection in the list is made. With this in mind, I will be able test the action of "a" being selected, using the method setSelectedIndex(index). valueChanged(...) will detect the change made from the call: list.setSelectedIndex(...)

public class GUI implements ListSelectionListener{
    String[] letters = {"a", "b", "c"};
    JList list = new JList(letters);
    list.addListSelectionListener(this);

    public void valueChanged(ListSelectionEvent e){
        if(list.getSelectedValue().equals("a")){
            System.out.println("Success");
        }else{
            System.out.println("Fail");
        }
    }
}

then from my test class

public class GUITest{
    @test
    void testListSelection(){
        GUI t = new GUI();
        t.list.setSelectedIndex(0);
        assert(whatever test your doing);
    }
}

The if statement for "a" as selected value was covered during a JUnit test.