将选定的ID传递给另一个班级

时间:2017-01-04 04:55:34

标签: java swing

我正在尝试使用Department类返回我JComboBox的选定ID,因为它是返回id的引用。但是当我试图将它返回到另一个类并使用它时。它只打印第一个索引,不会听我在JComboBox中执行的Action。

public class Frame extends JInternalFrame
{
   JComboBox cbDepartment;
   public Frame()
   {
     super("Frame",true,true,true,true);
     addToPane(getContentPane());
     setVisible(true);
     pack();
   }


   private void addToPane(final Container pane)
   {
      JPanel panel = new JPanel();
      pane.add(panel);

      cbDepartment.setActionCommand("Department");
      cbDepartment.addActionListener(listener);

      panel.add(cbDepartment);

   }

   ActionListener listener = new ActionListener() 
   {
      @Override
      public void actionPerformed(ActionEvent e) 
      {
         if("Department".equals(e.getActionCommand())) 
         {
            Department item = (Department) cbDepartment.getSelectedItem();
            int departmentId = item.getId();

            System.out.println("Your id is " +departmentId);
         }
      }
   }
   //RETURNING FOR ABLE TO USE IN ANOTHER CLASS
   public int getSelectedItem()
   {
      Department item = (Department) cbDepartment.getSelectedItem();
      return item.getId();
   }
}

public class Model
{
   Frame theView;
   public class Model(Frame theView)
   {
      this.theView = theView;
      print();
   }

   public void print()
   {
      int id = theView.getSelectedItem();
      System.out.println(id);
   }
}

正如您在上面看到的print()方法只获得第一个索引,即使我注册了JComboBox ActionListener任何原因? :)

1 个答案:

答案 0 :(得分:0)

您可以尝试使用

为组合框提供类似DefaultComboBoxModel的模型
cbDepartment.setModel()

,然后在组合框上使用函数.getmodel(),您可以获得模型,然后获取所选项目。