Java tutorial
//package com.java2s; /* * * Copyright (C) 2005-2008 Yves Zoundi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * under the License. */ import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import javax.swing.JList; import javax.swing.ListCellRenderer; import javax.swing.ListModel; public class Main { /** * * @param list * @param point * @return */ public static int loc2IndexFileList(JList list, Point point) { int index = list.locationToIndex(point); if (index != -1) { Object bySize = list.getClientProperty("List.isFileList"); if (bySize instanceof Boolean && ((Boolean) bySize).booleanValue() && !pointIsInActualBounds(list, index, point)) { index = -1; } } return index; } /** * * @param list * @param index * @param point * @return */ public static boolean pointIsInActualBounds(JList list, int index, Point point) { ListCellRenderer renderer = list.getCellRenderer(); ListModel dataModel = list.getModel(); Object value = dataModel.getElementAt(index); Component item = renderer.getListCellRendererComponent(list, value, index, false, false); Dimension itemSize = item.getPreferredSize(); Rectangle cellBounds = list.getCellBounds(index, index); if (!item.getComponentOrientation().isLeftToRight()) { cellBounds.x += (cellBounds.width - itemSize.width); } cellBounds.width = itemSize.width; return cellBounds.contains(point); } }