import java.awt.Component;   
import java.awt.event.ActionEvent;   
import java.awt.event.ActionListener;   
  
import javax.swing.*;   
  
public class TestList extends JList{   
    public TestList() {   
        this.setCellRenderer(new TestCellRender());   
        DefaultListModel m = new DefaultListModel();   
        this.setModel(m);   
        m.addElement("fasdf");   
        m.addElement("aaa");   
    }   
       
    class TestCellRender extends JButton implements ListCellRenderer{   
           
        public TestCellRender(){   
            addActionListener(new ActionListener(){   
                public void actionPerformed(ActionEvent e) {   
                    System.out.println("1 actionPerformed:" + getText());   
                }   
  
            });   
        }   
           
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {   
            setText(index+"");   
            return this;   
        }   
           
            
  
    }   
       
    public static void main(String[] args) {   
        JFrame f = new JFrame();   
        f.getContentPane().add(new TestList());   
        f.setSize(400,300);   
        f.setLocationRelativeTo(null);   
        f.setVisible(true);   
    }   
}  
怎么点击按钮不触发ActionListener事件啊

解决方案 »

  1.   

    这样写看能不能行
    public TestCellRender() {
    addListSelectionListener(new ListSelectionListener() {

    @Override
    public void valueChanged(ListSelectionEvent arg0) {
    System.out.println("1 actionPerformed:" + getText());

    }
    });
    }
      

  2.   

      public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {   
                setText(index+"");   
                return this;   
            }   
    这样写没有意义啊,你可以setText(value+"");