Java 从Jlist获取对象的实例
上面的代码在双击jList时会在其中获取一个项,并使用setText和item.toString()设置一个Jlabel 因此,它将对象的标签设置为字符串() 这是可行的,但我正在尝试将java.lang.object转换为类“Location”类的实例,而不仅仅是object类型的实例。 由于我无法获取该类getName()等中的方法,因此只能获取toString方法 我该怎么办, 谢谢试试看Java 从Jlist获取对象的实例,java,object,instance,jlist,Java,Object,Instance,Jlist,上面的代码在双击jList时会在其中获取一个项,并使用setText和item.toString()设置一个Jlabel 因此,它将对象的标签设置为字符串() 这是可行的,但我正在尝试将java.lang.object转换为类“Location”类的实例,而不仅仅是object类型的实例。 由于我无法获取该类getName()等中的方法,因此只能获取toString方法 我该怎么办, 谢谢试试看 if(evt.getClickCount() == 2){ int index = locLst.l
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);
}
然后您可以调用item.getName()
等等,试试看
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);
}
然后,您可以调用
item.getName()
等,如果您不确定对象的运行时类型,您可以使用instanceof检查它:
Location item = (Location) dlm.getElementAt(index);
如果不确定对象的运行时类型,可以使用instanceof检查:
Location item = (Location) dlm.getElementAt(index);