java - 转换对象时 event.getItem() 和comboBox.getSelectedItem() 之间有什么区别

标签 java swing events numbers jcombobox

我有一个带有组合框的面板。我正在向组合框添加 ID 号。但在添加任何 id 之前,我添加一个空字符串来知道没有选择 id。

JComboBox jcPatientIds;
JPanel patientPanel;

public void updateIdsInComboBoxes(ArrayList<Integer> items)
{
    getJcPatientIds().addItem("");
    if (items.size() > 0)
    {
        for (Integer item : items)
        {
            getJcPatientIds().addItem(item);
        }
    }
    getPatientPanel().add(getJcPatientIds());
}

public JComboBox getJcPatientIds()
{
    if(jcPatientIds == null)
    {
    jcPatientIds = new JComboBox();
    jcPatientIds.setBounds(250, 20, 100, 20);
    }
    return jcPatientIds;
}

public JPanel getPatientPanel()
{
    if(patientPanel == null)
    {
        patientPanel = new JPanel();
    }
    return patientPanel;
}

现在,我有这样的监听器类。而且它工作正常,没有出现任何错误

@Override
public void itemStateChanged(ItemEvent e)
{
    /*The event triggers for both deselected and selected item
    Here only the   selected event will be triggered with value 1
                    deselected event has a value 2*/
    if (e.getStateChange() == 1)
    {
        if (e.getItem().equals(""))
        {
            // Some stuff
        }
        else
        {
        System.out.println((int) e.getItem());
            // Some other stuff
        }
    }
}

但是,如果我在 Combobox 上使用 getSelectedItem。我收到 ClassCastException。这里有什么问题

@Override
public void itemStateChanged(ItemEvent e)
{
        if (getJcPatientIds.getSelectedItem().equals(""))
        {
            // Some stuff
        }
        else
        {
        System.out.println((int) getJcPatientIds.getSelectedItem()); // Here I am getting ClassCastException
            // Some other stuff
        }
    }
}

错误

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at hospitalApp.common.PatientController.itemStateChanged(PatientController.java:71)
at javax.swing.JComboBox.fireItemStateChanged(JComboBox.java:1225)
at javax.swing.JComboBox.selectedItemChanged(JComboBox.java:1273)
at javax.swing.JComboBox.contentsChanged(JComboBox.java:1329)
at javax.swing.AbstractListModel.fireContentsChanged(AbstractListModel.java:118)
at javax.swing.DefaultComboBoxModel.setSelectedItem(DefaultComboBoxModel.java:93)
at javax.swing.JComboBox.setSelectedItem(JComboBox.java:578)
at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:624)
at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(BasicComboPopup.java:835)
at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:290)
at java.awt.Component.processMouseEvent(Component.java:6516)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(BasicComboPopup.java:499)
at java.awt.Component.processEvent(Component.java:6281)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4872)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:747)
at java.awt.EventQueue.access$300(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:706)
at java.awt.EventQueue$3.run(EventQueue.java:704)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:720)
at java.awt.EventQueue$4.run(EventQueue.java:718)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:717)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

最佳答案

同样,我会避免用整数和字符串填充组合框。坚持使用 Integer,实际上将 JComboBox 声明为使用 Integer 作为其通用类型的通用对象:JComboBox<Integer> 。为空元素添加 null,然后检查 null:

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

public class Foo2 extends JPanel {
   DefaultComboBoxModel<Integer> jcPtIdModel = new DefaultComboBoxModel<>();
   JComboBox<Integer> jcPtIdCombo = new JComboBox<>(jcPtIdModel);

   public Foo2(List<Integer> ids) {
      if (ids != null) {
         updateIds(ids);
      }
      add(jcPtIdCombo);

      jcPtIdCombo.addItemListener(new MyItemListener());
   }

   public void updateIds(List<Integer> ids) {
      jcPtIdModel.removeAllElements();
      jcPtIdModel.addElement(null);
      for (Integer id : ids) {
         jcPtIdModel.addElement(id);
      }
   }

   private class MyItemListener implements ItemListener {
      @Override
      public void itemStateChanged(ItemEvent e) {
         //!! if (jcPatientIds.getSelectedItem().equals("")) {
         if (jcPtIdCombo.getSelectedItem() == null) {
            // Some stuff
         } else {
            // Here I am getting ClassCastException
            System.out.println((int) jcPtIdCombo.getSelectedItem());
            // Some other stuff
         }         
      }
   }

   private static void createAndShowGui() {
      ArrayList<Integer> items = new ArrayList<>();
      for (int i = 0; i < 10; i++) {
         items.add(i);
      }

      Foo2 mainPanel = new Foo2(items);

      JFrame frame = new JFrame("Foo2");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

我还看到您使用 setBounds(...)我强烈建议你不要这样做。而空布局和 setBounds()对于 Swing 新手来说,Swing GUI 似乎是创建复杂 GUI 的最简单、最好的方法,您创建的 Swing GUI 越多,在使用它们时遇到的困难就越严重。当 GUI 调整大小时,它们不会调整组件的大小,它们是增强或维护的皇家女巫,放置在滚动 Pane 中时它们完全失败,在所有平台或与原始分辨率不同的屏幕分辨率上查看时,它们看起来非常糟糕.

关于java - 转换对象时 event.getItem() 和comboBox.getSelectedItem() 之间有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31204613/

相关文章:

java - jQuery AJAX 调用 Java 方法

java - 在 MessageFormat 的 .properties 文件中测试空参数

java - 使用 swingworker 线程更新 UI

VB.NET:SelectedIndexChanged 多次触发

Laravel Notifications Listener 在实现队列时没用

java - ByteArrayOutPutSteam 到 Byte[] 未按预期工作

java - 我的 BMI 计算器出了什么问题?

java - 如何将事件与对象关联起来?

java - Swing 组件由于方法很少而卡住

java - 具有 id 的 jtextfields 行