0

我是 Java 新手,遇到了这样的问题;我有一个桌面应用程序,JFrame 中有 2 个 jComboBox。其中一个 jComboBox 是从 Personel Table 中保存 Personels,另一个是 Personel 的标题。当 jComboBox1 的选定索引发生更改时,它将获得 personelid 并用它的标题填充 jComboBox2。就是这样简单。但是当所选索引更改它用标题填充但显示类似Ljava.lang.Object.xxxxx ...

错误 http://img243.yukle.tc/images/7070error.jpg

这是我的代码;

  if (jComboBox1.getSelectedItem() !=null) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("SwingDenemePU");
    EntityManager em = emf.createEntityManager();
    Query sorgu = em.createQuery("from Personel p,Unvan u where  p.unvanID = u.unvanID and u.unvanID=:id");

int id = ((Unvan)jComboBox1.getSelectedItem()).getUnvanID();

   sorgu.setParameter("id", id);

   personelList = sorgu.getResultList();

    Object[] items = new Object[personelList.size()];

    for (int i = 0; i < personelList.size(); i++) {
items[i] = personelList.get(i);
    }
    DefaultComboBoxModel def = new DefaultComboBoxModel(items);
    jComboBox2.setModel(def);

如果我将 items[i] = personelList.get(i) 更改为;

            Personel personel = personelList.get(i);
        items[i]=personel.getPersonelAdSoyad();

我在线程“AWT-EventQueue-0”中遇到异常 java.lang.ClassCastException: [Ljava.lang.Object; 无法转换为 DBClasses.Personel 错误。

4

2 回答 2

1

默认组合框渲染器仅调用模型中包含的 Object 的 toString() 方法。因此,当您将 String 添加到模型时,您会看到 String 的值,因为这就是 toString 方法返回的内容。

如果您在模型中存储个人对象,那么您有两种选择:

a) 将 toString() 方法添加到 Personel 类 b) 创建自定义渲染器以显示来自 Personel 类的属性。

阅读 JComboBox API,您将找到关于“如何使用组合框”的 Swing 教程的链接,该教程提供了自定义渲染器的示例。

于 2009-07-05T22:30:57.060 回答
1

您的查询显示不正确,不确定您的映射是什么,但请尝试类似以下的内容:

    Query sorgu = em.createQuery("select p from Personel p,Unvan u where p.unvanID = u.unvanID and u.unvanID=:id");

或者

    Query sorgu = em.createQuery("from Personel p where p.unvanID=:id");
于 2009-07-05T22:48:12.330 回答