以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;
}
}