-1

下面是 的源代码UseTest.java。为什么它不起作用?

import javax.swing.* ;
import java.awt.* ;
import java.awt.event.* ;

class Test implements ActionListener{
 JFrame f ;
 JPanel p ;
 JComboBox cb ;
 JLabel l ;

 Test(){
  f = new JFrame("Test") ;
  f.setSize(200, 200) ;

  p = new JPanel() ;
  p.setLayout(new GridLayout(2, 1)) ;

  cb = new JComboBox() ;

  cb.addActionListener(this) ;

  for(int i = 1 ; i <= 20 ; i++)
   cb.addItem(i + "") ;

  //cb.addActionListener(this) ; //doesn't throws exception here


  l = new JLabel() ;
  l.setForeground(Color.red) ;

  p.add(l) ;
  p.add(cb) ;

  f.add(p) ;

  f.setVisible(true) ;
 }

 public void actionPerformed(ActionEvent ae){

  if(cb.getSelectedItem() != null){
   display() ;
  }
 }

 private void display(){
  String str = "" ;
  str = "Combo selection changed to : " + cb.getSelectedItem() ; 
  l.setText(str) ;
  System.out.println(str);
 }
}

public class UseTest{
 public static void main(String args[]){
  Test t = new Test() ;
 }
}
4

5 回答 5

4

一切正常,侦听器已正确添加到 JComboBox。

问题是当您向组合框调用 addItem 时,会触发 contentChanged 事件并调用您的 test#actionPerformed 方法,该方法尝试执行

l.setText(str);

但是 l 是在 cb.addItem 循环之后初始化的 JLabel。因此,当调用事件处理程序时,l 仍然为 null,因此出现 NullPointerException。

于 2010-02-04T06:15:27.223 回答
2

运行您的代码,我得到一个与您的 JLabel 相关的 NullPointerException。这在第一次调用 ActionListener 时尚未初始化 - 当您添加您的第一个项目时,会添加并因此更改选择。

于 2010-02-04T06:15:41.837 回答
1

How to Use Combo Boxes中有一个很好ComboBoxDemo的内容。

于 2010-02-04T15:23:02.420 回答
0

像您一样实现 ActionListener 并不是一种常见的模式。

您应该更好地编写如下代码:

cb.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent ae){

  if((JComboBox)ae.getSource()).getSelectedItem() != null){
   //Do your stuff
  }
 }
});
于 2010-02-04T08:48:28.180 回答
0

您可能想尝试添加一个 ItemListener。

于 2010-02-04T06:10:52.820 回答