简体   繁体   English

从Jlist获取对象的实例

[英]Getting the instance of an object from a Jlist

if(evt.getClickCount() == 2){
int index = locLst.locationToIndex(evt.getPoint());
ListModel dlm = locLst.getModel();
Object item = dlm.getElementAt(index);;
locLst.ensureIndexIsVisible(index);
System.out.println("Double clicked on " + item);
//Location loct = item.getClass();
DeedCard.setVisible(true);
TitleDeedLbl.setText(item.toString());
System.out.println(item.getClass);
item.equals(loc);
System.out.println(loc);
System.out.println(ha);
}

The above code gets an item in a jList when you double click on it, and sets a Jlabel with setText and item.toString() so it sets the label of the object toString(). 上面的代码双击时会在jList中获得一个项目,并使用setText和item.toString()设置Jlabel,从而将对象的标签设置为toString()。

this works, but i'm trying to convert a java.lang.object to an instance of the class "Location" class, not of just type object. 这可行,但是我正在尝试将java.lang.object转换为“ Location”类的实例,而不仅仅是类型为object的实例。 as i can't get the methods that are in that class getName() etc, only the toString method what do i do, thanks 因为我无法获取该类的getName()等中的方法,所以只有toString方法我该做什么,谢谢

Try 尝试

Location item = (Location) dlm.getElementAt(index);

and then you can call item.getName() etc., 然后您可以调用item.getName()等,

If you aren't sure about the runtime type of an object you can check it with instanceof : 如果不确定对象的运行时类型,可以使用instanceof进行检查:

Object obj = dlm.getElementAt(index);
if (obj instanceof Location){
 Location item = (Location) obj;
}

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

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