Reputation: 2029
I'm looking for a way to make a JList
always toggle the selection for the clicked item without deselecting the others, the same way as ctrl click works.
The ListSelectionModel
seems to be the right way to go but I can't figure out what has to be configured in there.
How to make a JList behave on click the same way as on ctrl click?
Upvotes: 2
Views: 2016
Reputation: 39197
You can use the following ListSelectionModel
:
list.setSelectionModel(new DefaultListSelectionModel(){
@Override
public void setSelectionInterval(int start, int end) {
if (start != end) {
super.setSelectionInterval(start, end);
} else if (isSelectedIndex(start)) {
removeSelectionInterval(start, end);
} else {
addSelectionInterval(start, end);
}
}
});
Upvotes: 5
Reputation: 168
you have to make your own ListSelectionModel. try it.
list.setSelectionModel(new DefaultListSelectionModel()
{
@Override
public void setSelectionInterval(int index0, int index1)
{
if(list.isSelectedIndex(index0))
{
list.removeSelectionInterval(index0, index1);
}
else
{
list.addSelectionInterval(index0, index1);
}
}
});
Upvotes: 4
Reputation: 109813
maybe this code can do that correctly
import java.awt.Component;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class Ctrl_Down_JList {
private static void createAndShowUI() {
String[] items = {"Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"};
JList myJList = new JList(items) {
private static final long serialVersionUID = 1L;
@Override
protected void processMouseEvent(MouseEvent e) {
int modifiers = e.getModifiers() | InputEvent.CTRL_MASK;
// change the modifiers to believe that control key is down
int modifiersEx = e.getModifiersEx() | InputEvent.CTRL_MASK;
// can I use this anywhere? I don't see how to change the modifiersEx of the MouseEvent
MouseEvent myME = new MouseEvent((Component) e.getSource(), e.getID(), e.getWhen(), modifiers, e.getX(),
e.getY(), e.getXOnScreen(), e.getYOnScreen(), e.getClickCount(), e.isPopupTrigger(), e.getButton());
super.processMouseEvent(myME);
}
};
JFrame frame = new JFrame("Ctrl_Down_JList");
frame.add(new JScrollPane(myJList));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowUI();
}
});
}
Upvotes: 2