开发者

Java - Check for selection on JList

Is there a way to see if my JList list is being selected or not?

I say this because I have a JList and JTextfield and when I type "F" in the JList to do a keyeve开发者_StackOverflow中文版nt action.. the letter F gets typed into the JTextField after I focus on it.

For example: Let's say I go to JTextField and type "hi". I go back to my JList and click on selected item and press "F" to delete that from list... well then in JTextField... I would also type "F" even though I am on JList.

Get what I am saying?


Use getSelectedIndex() or isSelectionEmpty() function of the JList.


Using a getSelectedIndex() is the easiest method.

Let's say you have a list of objects MyClass which you want to put in the JList:

List<MyClass> myClassList = new ArrayList<MyClass>();
// myclass.add ....

JList jList = new JList(myClassList.toArray());

Now, to get the selected element:

function MyClass getSelectedElement(){
    int index = jList.getSelectedIndex();
    if (index < 0){
        System.out.println("Nothing selected.");
        return null;
    }
    else{
        return myClassList.get(index);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜