7

我有:

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

这会在 jdk7 中导致以下编译器警告:

JComboBox 是一种原始类型。应该参数化对泛型类型 JComboBox 的引用

我试图将其参数化为:

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

但这仍然留下以下编译器警告:

类型安全:从 Object 到 JComboBox 的未经检查的强制转换

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

4

4 回答 4

4

我很欣赏这种方法。它避免了任何类型转换并且易于阅读。

我改进了我的答案,现在它没有给你编译器警告。JComboBox 的类型现在设置为字符串。要获得选定的项目,您必须通过 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);
  }
}
于 2012-10-05T01:59:48.623 回答
1

唯一的出路是获取对您的类型的引用JComboBox

要么这样

JComboBox<String> myStringCb = new JComboBox<String>();
...
myStringCb.addActionListener(new CustomerActionListener(myStringCb);

和你一起ActionListener

class CustomerActionListener implements ActionListener {

  private JComboBox<String> cb;

  public CustomerActionListener(JComboBox<String> cb) {
    this.cb = cb;
  }

  @Override
  public void actionPerformed(ActionEvent event) {
    if(event.getSource()==cb) {
       // Here you can do something with the typed cb
    }
  }
}

ActionListener或者,另一种解决方案是使用带有引用的匿名final

final JComboBox<String> myStringCb = new JComboBox<String>();
myStringCb.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent e) {
        // Here you can refer directly to myStringCb
    }

});
于 2012-10-05T08:11:26.073 回答
0

试着检查一下:

一个非常有用的链接表单 StackOverflow

简而言之,Java 编译器不知道您要转换的对象是什么对象,因此它不喜欢一言不发地进行转换,它必须告诉您您可能犯了一个错误(但是您确实知道您要投射的对象是哪种类,所以不要介意)添加 @SuppressWarning("unchecked")

于 2012-10-05T00:54:22.287 回答
0

另一个解决方案

您还可以使用Java 通配符模式:

class CustomerActionListener implements ActionListener
{
  @Override
  public void actionPerformed(ActionEvent event)
  {
    JComboBox<?> cb = (JComboBox<?>)event.getSource();
    .. do something
  }
}
于 2020-08-26T19:17:56.553 回答