好的,所以我认为我的问题源于对 JList实际在做什么缺乏基本的理解。
我有一个简单的示例类MyList
。
package test;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
public class MyList extends JList<String> {
public MyList(Vector<String> myStrings){
super(myStrings);
this.setCellRenderer(new ListCellRenderer<String>(){
@Override
public Component getListCellRendererComponent(
JList<? extends String> list, String value, int index,
boolean isSelected, boolean cellHasFocus) {
String myString = value.toString();
return new JLabel(myString+" (idx "+index+")");
}
});
this.addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(MouseEvent e) {
MyList p = (MyList) e.getSource();
Component c = p.findComponentAt(e.getX(), e.getY());
System.out.println("am clicking on "+c.getClass()+" in "+p.getClass());
}
});
}
public static void main(String[] args){
Vector<String> myStrings = new Vector<String>();
myStrings.addAll(Arrays.asList("str 1","str 2","str 3"));
MyList mine = new MyList(myStrings);
JFrame myFrame = new JFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(500, 500);
myFrame.add(mine);
myFrame.setVisible(true);
}
}
单击JLabel
列表中的任何内容的输出是相同的:
am clicking on class test.MyList in class test.MyList
我期望它是:
am clicking on class javax.swing.JLabel in class test.MyList
我认为这与 ListCellRenderer 的工作方式有关,但我不确定。p.findComponentAt(e.getX(), e.getY());
为什么我没有从JLabel中取回组件?这里发生了什么?