Overriding JList selection

Hello,
I am displaying a JList loaded with Strings inside a scrollpane. I want to make it such that clicking an item selects it, clicking it again unselects it, and multiple items can be selected at any one time. For this I wrote a MouseAdapter
public class ListListener extends MouseAdapter
  protected JList myList;
  protected String name;
  protected MyFrame parent;
  public ListListener(JList _myList, String _name, MyFrame _parent)
    myList = _myList;
    name = _name;
    parent = _parent;
  public void mouseClicked(MouseEvent e)
    int index = myList.locationToIndex(e.getPoint());
    if(e.getClickCount() == 1)
      parent.ClickItem(index, myList, name);
    else if(e.getClickCount() == 2)
      parent.DoubleClickItem(index, myList, name);
public class MyFrame extends JFrame
  protected static Vector<Integer> list1onVector = new Vector<Integer>(1, 1);
  protected static Vector<String> list1Vector = new Vector<String>(1, 1);
  protected static JList list1 = new JList();
  public MyFrame()
    //fill list1Vector
    list1.setListData(list1Vector);
    MouseListener list1Clicker = new ListListener(list1, "list1", this);
    list1.addMouseListener(list1Clicker);
  protected void ClickItem(int index, JList myList, String name)
    if(name.equalsIgnoreCase("list1")
      if(list1onVector.contains(Integer.valueOf(index)))
        list1onVector.remove(Integer.valueOf(index));
      else
        list1onVector.add(Integer.valueOf(index));
      inf[] list1Array = new int[list1onVector.size()];
      for(int i = 0; i < list1onVector.size(); i++)
        list1Array = list1onVector.get(i);
      myList.setSelectedIndices(list1Array);
      //do some processing based on what's selected
    else....
}That seems to work ok... most of the time. Every once in a while however, it will not select an entry or it will make some other entries deselected. Then on next click it shows it how it ought to be. I tried commenting out the code inside mouseClicked and selections were still going on, one at a time. So what I'm guessing is that the built in code that's handling the selections is messing with what I'm trying to do. I tried making my own JList object to deal with it
public class myJList extends JList
  public myJList()
  public void setSelectionIndex(int index)
    //do nothing here
  public void setSelectedObject(Object anObject, boolean shouldScroll)
    //do nothing here
}and using that instead of JList, but it didn't help. In fact, doesn't look like it's even going into those functions. What is actually originating the selection even, so I can cut it in the bud? Or is there a better way to do this? Any help is appreciated, thanks.

Well, I'll be darned, JList is in swing, not sure why i thought it was in awt.
I made the followowing change to mouseClicked, now looks like this:
Point point = e.getPoint();
int clickCount = e.getClickCount();
SafeClicks doSafeClick = new SafeClicks(myList, name, parent, point, clickCount);
SwingUtilities.invokeLater(doSafeClick);and ofcourse
protected class SafeClicks implements Runnable
  protected JList myList;
  protected String name;
  protected JFrame parent;
  protected Point point;
  protected int clickCount;
  public SafeClicks(JList _myList,
  String _name,
  JFrame _parent,
  Point _point,
  int _clickCount)
    myList = _myList;
    name = _name;
    parent = _parent;
    point = _point;
    clickCount = _clickCount;
  public void run()
    int index = myList.locationToIndex(point);
    if(clickCount == 1)
      parent.ClickItem(index, myList, name);
    else if(clickCount == 2)
     parent.DoubleClickItem(index, myList, name);
}Still the same issue. I think there IS an issue with thread timing and such, but I think the issue is that the JList object (default one) or one of its members is messing with the select at same time I am (and it's an issue if I go first it ends up bad, and if it goes first it ends up good). I think.

Similar Messages

  • Overriding JList selection behavior

    Hi,
    I am trying to implement a multiple selection JList that when you right/left click on an item it selects the item, if it is not selected. Deselect the item if it is already selected. The right click works fine, but the left click still works as the default. My code is as follow:
    String[] items={ "item 0", "item 1", "item 2", "item 3" , "item 4" };
    final JList l = new JList(items);
    l.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    l.setUI(new BasicListUI(){
    protected MouseInputListener createMouseInputListener()
    return new BasicListUI.MouseInputHandler()
    {//react on mouse pressed
    public void mousePressed(MouseEvent e)
    int row = convertYToRow(e.getY() );
    if(row >= 0)
    {    l.setValueIsAdjusting(true);
    if(l.isSelectedIndex(row) )
    l.removeSelectionInterval(row,row);
    else l.addSelectionInterval(row,row);
    public void mouseRelease(MouseEvent e)
    l.setValueIsAdjusting(false);
    Thanks you.

    I'm doing something similar with an inner class of my JList subclass. This code enables toggling and drag-selecting with button 1, and selection clearing with button > 1. Here's the inner class:
    class EasySelectListUI extends BasicListUI {
    protected MouseInputListener createMouseInputListener() {
    return new BasicListUI.MouseInputHandler() {
    public void mousePressed(MouseEvent e) {
    // clear selection first if button > 1
    if (e.getButton() != 1)
    clearSelection();
    int row = convertYToRow(e.getY());
    if (row >= 0) {
    setValueIsAdjusting(true);
    if (isSelectedIndex(row))
    removeSelectionInterval(row, row);
    else
    addSelectionInterval(row, row);
    public void mouseDragged(MouseEvent e) {
    // drag select only for button 1
    if ((e.getModifiers()&MouseEvent.BUTTON1_MASK) ==0)
    return;
    int row = convertYToRow(e.getY());
    if (row >= 0) {
    setValueIsAdjusting(true);
    addSelectionInterval(row, row);
    public void mouseReleased(MouseEvent e) {
    setValueIsAdjusting(false);

  • JList selection problems

    I'm having problems with JList selection - it's really wierd.
    I have a Jlist and on different selections I want to do stuff - well, I do see the GUI line get highlighted but everytime my ListSelectionListener is called the selected index stays 0.
    also, it always calls the ListSelectionListener twice for every selection I make.
    here's how my code looks:
    (typesList is my JList)
    typesList.setSelectedIndex(0);
    typesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    typesList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
          public void valueChanged(ListSelectionEvent e) {       
            int newSelection = typesList.getSelectedIndex(); //this returns always 0!        ...
          }

    Look at the line getValueIsAdjusting... (only one selection is processed. And, this code works and provides proper index.
        * Method to load all Tables from Database user
        public void loadTables() {
            // run Database request
            tableListModel = getListModelData("select object_name from user_objects where object_type = 'TABLE'");
            // now plug List with Model
            tableList = new JList(tableListModel);
            tableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            tableList.setSelectedIndex(0);
            //tableList.addListSelectionListener(this);
            tableList.addListSelectionListener(
                new ListSelectionListener() {
                    public void valueChanged( ListSelectionEvent e )
                        if(e.getValueIsAdjusting()) return;
                        String tablename = tableList.getSelectedValue().toString();
                        showColumnData(tablename);
                        displayAllTableData(tablename); //intensive (reworking)
            jScrollPane1.add(tableList);
            jScrollPane1.setViewportView(tableList);
            showColumnData(tableList.getSelectedValue().toString());
        }PiratePete
    http://www.piratepetesoftware.com

  • JList selection is listened twice

    Hi
    How to make JList selection listener to catch selection events for only one mouse click (mouse pressed or mouse released)

    Hi,
    you are right!
    first time e.getValueIsAdjusting() is true second time
    it is false. It does not corrspond to mousePressed or mouseReleased. I think the first is an item loosing selection and the second is another item getting selection (just a guess).
    Phil

  • How to 'veto' a jList selection change

    Hi All,
    I have a JList which I'm using as a record selector - so whenever my user selects an item on the list, the associated record is loaded up into the other controls on this form for editing. If the user edits any of the data items, I want to ask whether to save changes or not if another item is selected from the JList. So, I've added code in my 'selection changed' function to check for changes and show a 'yes/no/cancel' JOptionPane. The code for my 'yes' and 'no' respones work fine - either save the changes or not, then show the next record. My problem is handling if a user clicks cancel...
    If the user selects 'Cancel', I dont want any of my "show new record" code to execute (this is easy, I can just 'return' out of the function) but also I don't want the JList selection to change. I've tried calling setSelectedIndex() back to the originally selected item, but this in turn triggers my 'selection changed' function to be called again, which causes the user to be asked twice whether they want to save changes!
    So, what I'm after is a kind of beforeSelectionChanged event, which allows the possibility of denying the selection change - but it doesn't look like this exists! I vaguely remember another language (possibly C++/MFC) having this - the user's action could be ignored depending on the return value of the function. Can anyone offer a way of achieving this in Java?
    (It's been a while since I last touched Java, and I'm a complete n00b with Swing. Using NetBeans as my IDE.)
    Thanks in advance for any suggestions!
    Andy

    The way I do it, is to implement a VetoableSelectionModel similar to a bean with a vetoable property: on selection change it queries registered VetoableChangeListeners if they don't object and backs out if one of them barks.
    HTH
    Jeanette

  • How do I get my JList selection to Display after changing

    Granted there are probably 1,000,000,000 ways to write this code. The intent is to have a list of items that are assigned into catagories and when an item is selected the catagories that the item are in are highlighted in the list. This part works OK, as I change items the catagories change to reflect the current item catagories. I have two buttons to add catagories to items and remove catagories from items. The catagory to add is selected from a JCombo drop down list and then the user clicks the addcat button to add the catagory to the item.
    My problem is that the catagories in the JList (that also reside in a JScrollPane) do not show as selected after the list is updated. If I click the addcat button twice then the new catagory is highlighted. I thought that the suggestion in other forum messages to add revalidate and repaint would work so I tried that both at the list and the scrollpane level with no effect.
    -------------- Button Listener code --------------------
    addcat.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // get the curent catagory from the JCombo..
         String selectedcat = (String) fullcatlist.getSelectedItem();
    // get the curent Item from the JCombo..
         String selecteditem = (String) itemlist.getSelectedItem();
    // add item to catagory
         items.addItemCatagory(selecteditem,selectedcat);
    // debug
         product.setText(selectedcat +"::"+selecteditem);          
         int cnt = 0;
    // get a list of all catagories for this item
         String[] tgtList = catagories.getItemCatagories(selecteditem);
         // debug
         product.setText(selectedcat);          
    // get the JList list
         final ListModel lm = catlist.getModel();
    // get the list size
         int lsize = lm.getSize();
         String st ="";
         for (int j = 0; j < lsize;j++) {
    // get jth element of the list
         st = (String)lm.getElementAt(j);
    // compare it to the selected catagories list in if a match
    // set the index into the selected index array
         for (int k=0;k<tgtList.length;k++) {
         if ( st.compareTo(tgtList[k]) == 0 )
         lst[cnt++]=j;          
    //set up the selections
         int[] ilst = new int[cnt];
         for (int k = 0; k<cnt;k++)
         ilst[k] = lst[k];
    // enable teh selected indice
         catlist.setSelectedIndices(ilst);
    // paint the frame
         scrollPane.revalidate();
         scrollPane.repaint();
    --------------------- end code -----------------

    This might sound sarcastic, but it's not:
    I have no clue how to fix your code, but if your bored and want to try something, try copy-and-pasting that section right afterwards. You'd probably need to change some variables, but, again, I have no clue. This is all just a wild guess. Sorry I couldn't help you any more.

  • JList selection issue

    I am stuck again, this time with the behaviour of a JList!
    This is what I am trying to do: I want a selection list, in which any combination of items can be selected. And I want the deselection of a selected item to happen the same way the selection happens- when the user points on the item and clicks the mouse button. It seems that this behaviour is not predefined and multiple selection is only available through use of a key.
    Any ideas how to do this? Easy ways to do it are particularly welcome!
    Thanks a lot!

    If I really wanted this kind of behavior (simple mouse click to select/deselect) I would possibly use an array of JCheckBoxes in a JPanel (in a JScrollPane, if needed) in a GridLayout with one column (or maybe a vertical BoxLayout). To rephrase what E'hic said, introducing non-standard behavior can lead to a non-intuitive user experience.
    Another way could be to use a two column JTable with one Booolean and one String column. Or even only one column holding a custom class containing a boolean and String field, with a custom renderer and editor to show a JCheckBox with appropriate text set.
    Yes, a JList can be tweaked to do what you want, and I'm sure I've seen a solution for this here -- search the forum and you might find something. It's not what I would do, though.
    db

  • Modifying JList selection behavior

    What I want to do is change the selection behavior so that if the user clicks on the left half of the cell, the item is selected, but if the user clicks on the right half, the item is not selected. I already have the code to determine where the user clicked, but can't get the selection to not occur when I determine that the user clicked in the "non-selection area" right half.

    After overriding...
    public void setSelectedIndices(int[] indices)
    public void setSelectedValue(Object anObject, boolean shouldScroll)
    public void setSelectionInterval(int anchor, int lead)
    public void setSelectedIndex(int index)...it worked. I implemented each of these like this.
    public void methodX()
      if( clickOnSelectableRegion )
        super.methodX();
      clickOnSelectableRegion = true;
    }It is the responsibility of an outside MouseListener to determine if the click falls on a selectable region or not. If a click occurs that is not on a selectable region, the listener should call setOnSelectableRegion(false) on the List. I set the value back to true so the listener only has to notify the list of "ignorable" clicks.

  • JList to JList Selection Exchange

    I'm trying to build a GUI for a project where
    Selectable Values can be transfered from one list to
    another. I cant explaine what I mean to well so an ASCII picture may come in handy:
    From: --> To:
    JList <-- JList
    Note: --> and <-- are Buttons to do the swaping.
    I cant seem to Lay this out I've tried GridBag Grid, Box,
    Border as type of ways of laying it out Can someone please help.

    Ok new Quandry!
    How do I transfere JList Data to annother JList and remember avery & gt; is supposed to be > and any <x> are really [x];
    Here is my code I've tried but it doesn't work.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    class LtoL extends JFrame implements ActionListener
         public LtoL()
              String listtest[] = {"one","two","three","four","five","Six"};
              JList rightList = new JList();
              JLabel rightLabel = new JLabel("Selected Processes");
              JList leftList = new JList(listtest);
              JLabel leftLabel =  new JLabel("Available Processes");
              JPanel buttonPanel = new JPanel();
              JPanel buttonPanelNorth =  new JPanel();
              JPanel buttonPanelSouth =  new JPanel();
              JPanel rightSide = new JPanel();
              JPanel leftSide = new JPanel();
              JButton toRight = new JButton("Add Process");
              JButton froRight =  new JButton("Remove Process");
              JButton nextPage =  new JButton("Continue");
              toRight.addActionListener(this);
              froRight.addActionListener(this);
              rightSide.setLayout(new BorderLayout());
              leftSide.setLayout(new BorderLayout());
              rightSide.add(rightLabel,BorderLayout.NORTH);
              rightSide.add(rightList,BorderLayout.CENTER);
              leftSide.add(leftLabel,BorderLayout.NORTH);
              leftSide.add(leftList,BorderLayout.CENTER);
              buttonPanelNorth.setLayout(new BorderLayout());
              buttonPanelSouth.setLayout(new BorderLayout());
              buttonPanel.setLayout(new GridLayout(2,0));
              buttonPanelSouth.add(toRight,BorderLayout.NORTH);
              buttonPanelSouth.add(nextPage,BorderLayout.SOUTH);
              buttonPanelNorth.add(froRight,BorderLayout.SOUTH);
              buttonPanel.add(buttonPanelNorth);
              buttonPanel.add(buttonPanelSouth);
              JPanel mainPanel =  new JPanel();
              mainPanel.setBorder(new EmptyBorder(new Insets(5,5,5,5)));
              mainPanel.setLayout(new GridLayout(0,3));
              mainPanel.add(leftSide);
              mainPanel.add(buttonPanel);
              mainPanel.add(rightSide);
              this.getContentPane().add(mainPanel);
              //Placement 
              Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
              setLocation(dim.width/4-this.getWidth()/2, dim.height/4-this.getHeight()/2);
              //Actions
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              //Show it
              setSize(640,480);
              setResizable(true);
              setVisible(true);
         public void actionPerformed(ActionEvent e)
              if( e.getActionCommand().equals("Add Process"))
                   //on button Add :
              rightList.setSelectedIndices(leftList.getSelectedIndices());
              else
                   //on button remove
              leftList.setSelectedIndices(rightList.getSelectedIndices());
         public static void main(String args[])
              LtoL l = new LtoL();
    }I here are the errors i get as well when i try to compile it.
    cannot resolve symbol leftList or rightList why?

  • JList selection focus problem

    Hi,
    I'm trying to write a help viewer similar to a MS one. I would like to be able to type characters into a textfield,and as they are typed, the matching JList item is selected.
    This works, but the selected item in the JList is only painted as selected when it gains focus. Is there any way to make a JList item paint as if it is selected and has focus, even though another component actually has the focus?
    Thanks.

    Make a custom cellrenderer extending the DefaulListCellRenderer and let it do smething like the code below. The borders on cellHasFocus are my custom variants, but I guess it's easy to find the default ones if you like.
    Have a look in the tutorial about custom renderers and in the performande book at :
    http://java.sun.com/docs/books/performance/
    or more precisly at:
    http://java.sun.com/docs/books/performance/1st_edition/html/JPSwingModels.fm.html#1001816
    It's easy to make some errors in renderers... Never create any new objects and other things and you're halfway there.
      public Component getListCellRendererComponent(JList list, Object value,
           int index, boolean isSelected, boolean cellHasFocus)
              if (isSelected)
                 this.setBackground(list.getSelectionBackground());
                 this.setForeground(list.getSelectionForeground());
              else
                 this.setBackground(list.getBackground());
                 this.setForeground(list.getForeground());
              if (cellHasFocus)
                 this.setBorder(hasFocusBorder);
              else
                 this.setBorder(hasNotFocusBorder);
              return this;
       }

  • JList Selection

    Hello everyone,
    first of all, excuse me for my poor english.
    I have a JList contaning nearly 200 items and I would like the maximum selectable item count to be 5.
    I thought a good way to do that could be to add a listener to the list data and each time an event occurs on the list data run the getSelectedIndexes() method. Then if the result length is more than 5 the event could be canceled.
    But, I am not sure it's the best way to do that and most of all I don't know how to cancel and event.
    Could some help me please. Thank yopu very much.

    Thank you for your answer because the code you gave me is the one I use, so now I'm sure it's the good way to proceed.
    My problem is that I don't know what to do in remplacement of the comment. That's to say I don't know how to unselect the box just selected by the user witch is not necessary the one with the higher index.
    In this case: user selects items with following indexes : 1, 7, 8, 125, 130 and then a 6th: 34. The min index will be 1, the max index wille be 130, but how can I know that the last selected index is 34.
    That's why I wanted to "cancel" the event; in order to unselect the last selected item.
    Thank you

  • JList Selection Listener

    How can i add a listener to a JList so that it runs a method when the selection has changed? I have already looked at the tutorial but it seems to be over complicated for what i need.
    I have tried:
    addFinanceList.addListSelectionListener(new ListSelectionListener()
    public void valueChanged(ListSelectionEvent event)
    CP.getFinance().loadFinance((String)addFinanceList.getSelectedValue());
    updateDisplay();
    But this never executes.
    Can anyone help?

    Sure it never executes? If you select items in the
    list, what you've written looks correct. I'd shove a
    println or log message in the valueChanged method to
    see what's happening.Tried that...still nothing happens!

  • JList Selection Event

    Hi, here is one problem i am facing.
    i have a JList and i am using Selection Listener for that. Now selection listener has only one even in it valueChanged. which is only fired when some value is changed in the JList, i.e., if we select the same value twice consecutively, this event is fired only once only when that value is selscted for the first time. but i want this even to be fired every time i select a value (even twice or thrice consecutively). can u plz help me or tell me any other event?
    -Ashish

    problem is I cannot recieve which chat room is selected (let's say I don't know how to get it :) )Sorry I didn't get the humor :-( So let's try a dry answer:
    Try "jlist.getSelectedValue()" and cast it to the common supertype of all objects stuffed in the JList's model (I assume they are String or ChatRoom objects).
    and also selected index is appended twice when I click on any of them ? Can it be done by double click ?You receive two events (deselection of current item - selection of new item). You can distinguish them with event.getValueIsAdjusting().
    Brgds.

  • JList selection error

    Hi!
    I haveing great problems with getting the JList to function properly and dont understand why.
    The problem is that no selection of the JList can be performed at all, etc no highligting at all.
    Anyone who sees the error? This is my first time buliding this kind of object, so any suggestions to improvements is also welcome!
    Best regards Wargrammer
    code:
    public class GUI2 implements ListSelectionListener{
    private MyListModel JposListModel = new MyListModel();
    private JList JposAdapterList     = new JList(JposListModel);
          public GUI2(){
                         JposAdapterList.setCellRenderer(render);
         JposAdapterList.setBackground(Color.BLACK);
         JposAdapterList.setFocusable(true);
         JposAdapterList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         JposAdapterList.setSelectedIndex(0);
         JposAdapterList.addListSelectionListener(this);
        public void update(){
              JposListModel.updateList();
    class MyListModel extends DefaultListModel{
           void updateList(){
         Vector results = testResultModel.getTestResults();
         this.removeAllElements();
         for (int i = 0; i < results.size(); i++){                    
                        this.addElement(results.get(i));
         this.setSize(results.size());                              
    public class CellRenderer extends DefaultListCellRenderer {
                public Component getListCellRendererComponent(JList list,
         Object value,
         int index,                                        boolean isSelected,
         boolean hasFocus) {
                        JLabel label = new JLabel();
         if (value instanceof ObjectImpl) {
                      ObjectImpl temp = (ObjectImpl)value;
                      label.setText(temp.getTypeId() + " : " + temp.getLogicalName());
                       if(temp.getStatus()< 0){
              label.setForeground(Color.RED);
           return label;
    }

    The basic problem is that you are not setting the fg/bg colours according to whether the cell is selected in your ListCellRenderer. If you look at the source code for DefaultListCellRenderer then you will see that it does this.
    More serious, though, is that you are extending DefaultListCellRenderer, which is itself a label and a suitable object to return but creating a new JLabel every time the renderer is called and returning that instead. This is not only pointless but wasteful.
    Try changing your code to either call the super class method and then do your own stuff on this or get the necessary highlight code ideas from the JDK source and extend JLabel yourself. In both cases, realise that the label is reused by swing whenever it wants to paint a cell, and you don't want to create a new one.

  • How to stop JList selection?

    Hi,
    Is it possible to stop the JList box selection? i.e. keep the selection at the old selection. I tried the following in the ListSelectionListener valueChanged() method:
    if (e.getValueIsAdjusting()){
    // Do something to the old selection
    // if something is wrong,
    list.setSelectionInterval(old_index, old_index);
    else {
    // do something to the new selection.
    But this is actually REVERTing the selection, but not STOPPing the new selection. Since it is in the valueChanged() method, I guess there is no way I could STOP the selection here.
    Does anybody know where and how to "veto" a list selection event? Note that this will be triggered by user's mouse click on the list box.
    Thanks!

    You'll have to do it in a new thread, try the SwingUtilities.InvokeLater method like this:
       if (e.getValueIsAdjusting()){
    // Do something to the old selection
    // if something is wrong,
           list.setSelectionInterval(old_index, old_index);
       } else {
           SwingUtilities.invokeLater(new Runnable() {
              public void run() {   
    // do something here
       };o)
    V.V.

Maybe you are looking for