一個非常類似的問題已被要求here,雖然我承認它,但問題的解決方案並不完全解決我的問題。點擊時,A JList
將選擇最接近鼠標點擊的索引列表項。 A JList
也會爲每次點擊+拖動事件觸發做到這一點。如何防止JList在拖動列表末尾時選擇元素?
我想阻止我的JList
在點擊+拖動事件點擊+拖動位置不在可見列表中時選擇項目。我將如何去做這件事?
我曾考慮重寫一個不同的方法,一個涉及點擊+拖動選擇列表項的事件。我想試試setSelectionInterval()
的方法。
JList<String list = new JList<String>(){
private static final long serialVersionUID = 1L;
@Override
public int locationToIndex(Point location) {
int index = super.locationToIndex(location);
if (index != -1 && !getCellBounds(index, index).contains(location)) {
clearSelection();
return -1;
//an excellent click-only solution to prohibit the selecting of
//items from beyond the visible list
}
else {
return index;
}
}
@Override
public void setSelectionInterval(int anchor, int lead) {
super.setSelectionInterval(anchor, lead);
System.out.println("setSelectionInterval");
}
};
我發現,每次我點擊提供的任何拖累顯示JList
,我得到我加入到上述方法「setSelectionInterval」的System.out的消息。在壓倒一切的方法方面,我不知道該從哪裏走。也許這不是我應該如何處理這個問題。在setSelectionInterval()
的源代碼中,我迷路了,試圖找到通向任何聽衆的方式,所以我來到了這裏。 :p
我非常感謝任何指向我應該看的地方或一個解決方案。提前致謝!
這是一個接近我設置的SSCCE示例。實際上,當點擊事件從列表項自身被觸發時,列表不會選擇一個項目。當點擊+拖動事件從列表項中被觸發時,我希望發生同樣的效果。
import java.awt.BorderLayout;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
public class TestMain {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel content = new JPanel(new BorderLayout());
String[] data = {"Luke", "Jeff", "Bryce"};
JList<String> list = new JList<String>(data){
private static final long serialVersionUID = 1L;
@Override
public int locationToIndex(Point location) {
System.out.println("location to index");
int index = super.locationToIndex(location);
if (index != -1 && !getCellBounds(index, index).contains(location)) {
clearSelection();
return -1;
}
else {
return index;
}
}
}
content.add(list, BorderLayout.CENTER);
frame.setContentPane(content);
frame.setSize(200,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
爲了更好地幫助越早,張貼[SSCCE(http://sscce.org/)。 – 2013-04-20 04:20:44
我不知道我會怎麼做,對不起。我無法得到我想要工作的東西。 – 2013-04-20 04:24:29
*「我無法得到我想要工作的東西」* SSCCE不必「工作」,但必須符合縮寫的條款。閱讀文章,如果有什麼你不明白的,問。我很好解釋。 – 2013-04-20 04:26:55