通過mKorbel以本實施例中作爲一個例子後選自:行添加默認選擇兩行
我已經實現了創建通過使用由mKorbel建議的機制所需的行爲。只要我有一行塗成綠色(未選中),這將起作用。但是,如果我添加一行,選擇它,然後添加一個新行,它工作正常,我得到一個新的未選中的行。如果我添加了第二行並選擇了它,那麼它會被正確地塗成紅色,但是在第二行(兩行紅色)之後添加更多行時,它們都會默認選中,這不是我想要的。我希望所有的行都是綠色的,直到我點擊它們(雙擊)。有誰知道爲什麼會發生這種情況?爲什麼只要我沒有選擇1個單元格就可以工作?爲什麼如果我選擇了多於兩行或全部行,它會不斷在選定模式中添加新行?日Thnx
我的鼠標事件代碼如下:
m_list = new JList<String>(m_listModel)
{
private MyCellRenderer cellRenderer = new MyCellRenderer();
// emulate control down for multiple non contiguous selection on the
// list.
@Override
// TODO fix here
public void processMouseEvent(MouseEvent event) {
int modifiers = event.getModifiers() | InputEvent.CTRL_MASK;
m_myME = new MouseEvent((Component) event.getSource(),
event.getID(), event.getWhen(), modifiers,
event.getX(), event.getY(), event.getXOnScreen(),
event.getYOnScreen(), event.getClickCount(),
event.isPopupTrigger(), event.getButton());
//if clicked twice
if (event.getClickCount() == 2) {
//if the flag is set to true consume event
if ((MyCellRenderer.getFlag() == true)) {
m_urlName = MyCellRenderer.getValue();
m_myME.consume();
//initiate parsing
initiateParsing();
}else{
m_urlName = MyCellRenderer.getValue();
}
//if it is not consume it will emulate CTRL_MASK
if (!m_myME.isConsumed()) {
super.processMouseEvent(m_myME);
m_urlName = MyCellRenderer.getValue();
//initiate parsing process
initiateParsing();
}
}
}
};
中的CellRenderer的代碼如下:
public static class MyCellRenderer extends JLabel implements
ListCellRenderer {
private static final long serialVersionUID = 1L;
private static boolean myFlag = false;
private static String thisValue;
public MyCellRenderer() {
setOpaque(true);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
setText(value.toString());
Color background = null;
Color foreground = null;
if (isSelected == true) {
background = Color.RED;
foreground = Color.WHITE;
myFlag = true;
} else {
background = Color.GREEN;
foreground = Color.BLACK;
myFlag = false;
}
setBackground(background);
setForeground(foreground);
public static class MyCellRenderer extends JLabel implements
ListCellRenderer {
private static final long serialVersionUID = 1L;
private static boolean myFlag = false;
private static String thisValue;
public MyCellRenderer() {
setOpaque(true);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
setText(value.toString());
Color background = null;
Color foreground = null;
if (isSelected == true) {
background = Color.RED;
foreground = Color.WHITE;
myFlag = true;
} else {
background = Color.GREEN;
foreground = Color.BLACK;
myFlag = false;
}
setBackground(background);
setForeground(foreground);
// the string where its pointing at
thisValue = value.toString();
m_index = index;
return this;
}
public static boolean getFlag() {
return myFlag;
}
public static String getValue() {
return thisValue;
}
}