Java Swing - 如何在ActionListener中处理泛型 [英] Java Swing - How to handle generics in ActionListener

查看:204
本文介绍了Java Swing - 如何在ActionListener中处理泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

 类CustomerActionListener实现ActionListener 
{
@Override
public void actionPerformed(ActionEvent event)
{
JComboBox cb =(JComboBox)event.getSource();
..做某事
}
}

在jdk7中发出编译器警告:



JComboBox是一种原始类型。参考泛型类型JComboBox应该被参数化



我尝试过参数化为:

 的JComboBox<字符串> cb =(JComboBox< String>)event.getSource(); 

但是,这仍然会产生以下编译器警告:



类型安全性:未检查从Object转换为JComboBox

因此我不确定如何消除编译器警告。 ..

解决方案

我赞成这种方法。它避免了任何Typecasts,并且易于阅读。



我改进了我的答案,现在它不会给您编译器警告。 JComboBox的类型现在设置为String。要获取选定的项目,您必须通过ComboBoxModel。

 类CustomerActionListener实现ActionListener 
{
private JComboBox< String>组合框;
public CustomerActionListener(JComboBox< String> comboBox){
this.comboBox = comboBox;
}
@Override
public void actionPerformed(ActionEvent event)
{
//只需使用comboBox
ComboBoxModel< String> model = comboBox.getModel();
int index = comboBox.getSelectedIndex();
String choosen = model.getElementAt(index);
System.out.println(你好,选择+选择);
}
}


I have:

class CustomerActionListener implements ActionListener
{
  @Override
  public void actionPerformed(ActionEvent event)
  {
    JComboBox cb = (JComboBox)event.getSource();
    .. do something
  }
}

Which causes the following compiler warning in jdk7:

JComboBox is a raw type. References to generic type JComboBox should be parameterized

I've tried to parameterize it to such that:

JComboBox<String> cb = (JComboBox<String>)event.getSource();

But this still leaves the following compiler warning:

Type safety: Unchecked cast from Object to JComboBox

Therefore I'm not sure how to eliminate the compiler warnings...

解决方案

I apreciate this approach. It avoids any Typecasts and is easy to read.

I improved my answer, now It doesn't give you Compiler Warnings. The Type of JComboBox is now set to String. To get the selected Item, you have to go through the ComboBoxModel.

class CustomerActionListener implements ActionListener
{
  private JComboBox<String> comboBox;
  public CustomerActionListener(JComboBox<String> comboBox){
    this.comboBox = comboBox;
  }
  @Override
  public void actionPerformed(ActionEvent event)
  {
    // Just use the comboBox
    ComboBoxModel<String> model = comboBox.getModel();
    int index = comboBox.getSelectedIndex();
    String choosen = model.getElementAt(index);
    System.out.println("Hey you choose "+choosen);
  }
}

这篇关于Java Swing - 如何在ActionListener中处理泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆