简体   繁体   English

如何编写自己的 ListSelectionEvent?

[英]How do I write my own ListSelectionEvent?

I made a GUI that holds a list.我制作了一个包含列表的 GUI。 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.我希望能够测试该操作,而无需通过 GUI 实际进行选择。 For example I have my GUI.java and a separate GUITest.java.例如,我有我的 GUI.java 和一个单独的 GUITest.java。 Id like to do something like我想做类似的事情GUITest.java

valueChanged() is a method from the java interface ListSelectionListener and only accepts parameters of type ListSelectionEvent. valueChanged() 是来自 java 接口 ListSelectionListener 的方法,仅接受 ListSelectionEvent 类型的参数。 So ultimately, how would I create my own ListSelectionEvent variable that holds the action that "a" was selected?所以最终,我将如何创建自己的 ListSelectionEvent 变量来保存选择“a”的操作?

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.当在列表中进行选择时,方法 valueChanged(ListSelectionEvent e) 会自动运行。 With this in mind, I will be able test the action of "a" being selected, using the method setSelectedIndex(index).考虑到这一点,我将能够使用 setSelectedIndex(index) 方法测试选择“a”的动作。 valueChanged(...) will detect the change made from the call: list.setSelectedIndex(...) valueChanged(...) 将检测调用中所做的更改: 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然后从我的测试 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.在 JUnit 测试期间涵盖了将“a”作为选定值的 if 语句。

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

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