Selection in JList

Hi!
I am using JScrollbar to hold the JList and i have set the property setVisibleRowCount to 1.
List contains the values from 0..1000, if i want the default value to be displayed in the JList is 21, i have set the ensureIndexVisible property to 21, but it is showing only the first item in the list i.e 0. But item 21 is selected.
Please help me regarding this,
Thanks in advance
Raghu

hi,
first of all I'd like to say that it is not such a good idea to limit the displayed rows in a JList to one - you should use JComboBox instead. Your question concerning ensureIndexIsVisible isn't very easy to reply to, because you didn't pass your source code along. Nevertheless I suppose that the reason for this behaviour is the following: you called this function before you provided the list with the data model or before you added the list to the scroll pane, because this method is no property accessor, as you assumed, but a simple function, which advices the viewport (in the scrollpane) to scroll to a specific position. Therefore a data model must be there and, of course the viewport. So ensure that you call this method after you added a data model and after you put the list into the scrollpane.
best regards, Michael

Similar Messages

  • How We can restrict the max no of Selections in JList

    Hi,
    How We can restrict the max. no of selections (at random selections) in JList (ex. max No of of selections is 3 in a JList of having 50 items.)
    Thanks for your advise in advance.

    Hello Satyaki De.
    Thank you very much for your suggestion but my Private information is totally apart from this question & I already I have changed each and every information from the question.
    Thanks
    Kamlesh Gujarathi
    [email protected]

  • Prevent Ctrl-A from selecting in JList

    How can I prevent Ctrl-A from causing all items
    in my JList to become selected?
    This may seem like a strange question, but I have
    a custom JList which uses a mouse listener to
    detect selections rather than its usual selection
    listener. Nevertheless, the Ctrl-A key combination
    still causes all items to be selected.
    How can I avoid this? I have tried simply
    unregistering the key combination:
    unregisterKeyboardAction(
    javax.swing.KeyStroke.getKeyStroke(
    java.awt.event.KeyEvent.VK_A,
    java.awt.Event.CTRL_MASK,
    false));
    But this has no apparent effect.
    b.c

    Thanks, Dave.
    I'm finding other inconsistent behaviour that is exacerbating the problem. If I close the last PDF file with ctrl-W, the search window stays open.  If I close the last PDF file from the task bar, boom, the search window gets clobbered too, which entails another lengthy re-search.

  • Selection of JList item

    hi friends
    i am using JList component.i have added many item in Jlist.by keyboard up and down arrow key i can make them highlighted and then select. but i want few item of JList never highlighted and select when i press up and down arrow key . For example, If i do not want to select 2nd item in the list then by pressing down arrow key selection should be jumped from first to third item skipping second item.
    How to do that?

    I might be wrong but I think you need to code for it.
    I have created a code using key binding. To use if you need to skip an item you need to hold down the control key and use the up and down arrow to navigate and once you have selected an item release control key and press enter, vice-versa.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ListFocusDemo extends JFrame {
        public void createAndShowUI() {
            final JList myList = new JList(new String[] {"My data 1","My data 2",
            "My data 3","My data 4"});
            JScrollPane scrollPane = new JScrollPane(myList);
            InputMap map = myList.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "myAction");
            myList.getActionMap().put("myAction", new AbstractAction() {
                public void actionPerformed(ActionEvent evt) {
                    int lead = myList.getLeadSelectionIndex();
                    if(lead > -1 && !myList.isSelectedIndex(lead)) {
                        myList.getSelectionModel().addSelectionInterval(lead, lead);
                    } else if(lead > -1 && myList.isSelectedIndex(lead)) {
                        myList.getSelectionModel().removeSelectionInterval(lead, lead);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(scrollPane, BorderLayout.CENTER);
            pack();
            setLocationRelativeTo(null);
            setVisible(true);
        public static void main(String[] args) {
            Runnable run = new Runnable() {
                public void run() {
                    new ListFocusDemo().createAndShowUI();
            SwingUtilities.invokeLater(run);
    }

  • Selecting a jlist item and placing it in view

    i have 100 items in a jlist. then i scrolled to the bottom of the list.....so now the first item is not in view anymore.
    i have a button on top that retrieves rows and rebuilds the jlist.
    which it does.
    however, if i am at the bottom of the list and hit the button i want the first item to be selected and viewed in the screen.
    dbase_list.setSelectedIndex(0); ---> selects the first item
    but its not in view till i scroll back up again.
    how do i select and place the first item in the users view after i hit the button? is there a method that does it?
    thanks

    Add this code in ur constrcutor
    list.setAutoscrolls(true);
    list.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(KeyEvent e) {
    list.ensureIndexIsVisible(list.getSelectedIndex());
    });

  • Multiple selection in JList

    How can I set up a JList that always uses multiple selection. That is, it acts as though the CTRL key is held down when the user selects items.

    Here's an example of multi-selection in a listbox, but using the shift key
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.applet.*;
    public class Multi extends Applet implements KeyListener
         List list = new List(5, true);
         public void init()
              createGUI();
              setSize(300,300);
              this.setVisible(true);
         public void createGUI()
              for (int j = 0; j < 20; j++)
                   list.addItem("TESTING MULTI-SELECTION IN A LIST");
              add (list);
              list.addKeyListener(this);
         public void keyReleased(KeyEvent e)
              int key = e.getKeyCode();
              if (key == KeyEvent.VK_SHIFT)
                   int itm[] = list.getSelectedIndexes();
                   for(int i = itm[0]; i < itm[1]; i++)
                        list.select(i);
         public void keyTyped(KeyEvent e){}
         public void keyPressed(KeyEvent e){}
    }

  • Can't select when JList populated by LOV

    I'm at a loss here...
    JDev 10.1.2.1 (1913)
    I'm creating a simple Swing Shuttle panel. I want standard action, i.e. when the 'shuttle' button is pressed, the selected items in JList1 move to JList2.
    I first created this with JList1 bound to a VO. I quickly realized that I couldn't remove elements from the list without removing the appropriate rows from VO...tried to do that but ran into errors.
    Ok, so i figured I'd create a programmatic VO and followed the documentation to populate this with a LOV from the db-backed VO attribute I want.
    The problem is that all list values are grayed out and un-selectable
    Steps:
    1 - Create DB-backed VO and programmatic-backed VO with same attributes (I created these using the Ename field from Scott.EMP)
    2 - Create JPanel
    3 - Find the programmatic-backed VO on the Data Control palette
    4 - Expand to find the attribute I want to show in my JList; select "Drag and drop as List"; drag onto my panel
    5 - Open the List binding editor from the Structure window
    6 - On the LOV Update attributes tab I select the DB-backed VO as the source and the programmatic VO as the target
    7 - On the LOV display attributes tab I shuttle over the attribute I want to display (Ename)
    I tried the three different selectionModes...I compared the properties of the VO-backed JList with the LOV-backed list and can't find a difference. I fooled around with the "Updatable" settings in the VO...
    Any ideas why this doesn't work as i expect?
    thanks
    John

    I'm not sure that there is anything in the ADF Bindings to help you here. What we have done is to programatically execute the query and add each Row to the JList. You will need a custom renderer to the JList so that the list knows which attribute from the Row to display. Then when you shuttle the row over, you just remove it from the first JList and add it to the 2nd JList. It is also very easy to create a generic ListCellRenderer that knows how to display Row objects. Here is one that we use:
    import java.awt.Component;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.ListCellRenderer;
    import oracle.jbo.Row;
    public class ADFRowListCellRenderer extends JLabel implements ListCellRenderer {
      private String attributeName = null;
      public ADFRowListCellRenderer(String attributeToDisplay) {
        this.attributeName = attributeToDisplay;   
      public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {  
        Row row = (Row) value;
        String fieldValue = null;
        if( row != null ) {
          Object objectValue = row.getAttribute(attributeName);  
          if( objectValue != null ) {
            fieldValue = objectValue.toString();  
        setText(fieldValue == null ? "" : fieldValue);
        setOpaque(true);
        setBackground(isSelected
               ? list.getSelectionBackground()
               : list.getBackground());
        setForeground(isSelected
               ? list.getSelectionForeground()
               : list.getForeground());    
        return this;
    }One thing to remember is that a Row instance has some internal id assigned to it, so if you re-execute the query, your list's Row references will be invalid. If you have to re-execute the query, then you will need to clear the JLists and reload the Rows.
    Hope this helps
    Erik

  • Multiple Selection with JList

    Hello!
    I have a Frame with a JList that needs to be able to do multiple slection. The JList ist filled with special names which are found when the user opens a certain file. (so a file-chooser is here too) When the User selects a name every paragraph containing that name should be posted in a textarea.
    However, when i run the program I can select multiple items, BUT it just recognises that the user selected one of the items, and I think it's the first one clicked.
    How can I change that? I have used getSelectedValues() but it just won't work...
    Can someone please help?
    Thanks

    So getSelectedValues() is only returning an array of size 1?
    Paul

  • Automatic Selection for JList

    Hi,
    How can I update the selection of a (SINGLE_SELECTION) JList automatically when scrolling up or down
    (for the next or previous item)?
    thanks
    Qusay

    Hi
    We have resolved this problem by creating a BDC.
    Thread Closed.
    Edited by: OmKarP on Nov 19, 2011 7:49 AM

  • Distinguishing user selections from programmatic selections in JList

    I have two jlists., and registered a subclass of ListSelectionListener on each list. When the user selects a record in the first list part of of the code I have written sets a selection on the second list which is correct, but then this triggers the listener on the second list to receive an event, and run its listener code which is not what I want.
    I want to be able to identify a list selection caused by the user selecting a record in the list rather than the a programmatic selection, so that i can ignore programmatic selections.
    Checking event.getSource() is no good as it always just returns the JList itself regardless of whether it has been done programtaically or by a user.
    I tried checking list.isFocusOwner() , figuring that only lists that had been user selected would be focus owner. This works for Windows but on MacOS, it doesnt work the frst time you select something from the list after moving from another component (it does work after that).
    How do i do this, thanks Paul

    an alternative is to set a flag
    boolean fromList1Listener = false;//class field scope
    list1Listener
      fromList1Listener = true;
      change list2 selection
      fromList1Listener = false;
    list2Listener
      if(fromList1Listener == false)
        normal code goes here
    }

  • MULTIPLE SELECTION of Jlist only with mouse

    I want select many items of Jlist but I need make only with the mouse.
    I cann�t use keyboard.
    I don�t know how do it, because I selected
    listSelectionModel.MULTIPLE_INTERVAL_SELECTION
    but I need do a click in the first item and press key shif + click in the last item.
    but I must do a program only with the mouse.
    how I can make it?
    thanks

    hi,
    heres a quick and dirty version:
    set an ListSelectionModel at your List that overwrites the DefaultListSelectionModel class like this:
    ListSelectionModel selectionModel = new DefaultListSelectionModel() {
    int anchor = -1;
    public void setSelectionInterval(int index1, int index2) {
    if( index1 == index2 ){
    if( anchor = -1 ) anchor = index1;
    super.setSelectionInterval(anchor, index2);
    }else {
    super.setSelectionInterval(index1, index2);
    public void setValueIsAdjusting(boolean b) {
    super.setValueIsAdjusting(b);
    if(!b) anchor = -1;
    as long as single list entries should be selected, while the mouse is dragged ( valueIsAdjusting ), the entry is added to a selection range instead.
    I didnt compile the code, so maybe there are some syntax struggles.
    if you want to do it the hard and stoney way you have to implement a new ui class, that accomplish your needs.
    regards,
    stefan

  • Selecting a JList with right-click

    What's the best way for a JList to select its value with a right-click. I plan on bringing up a JPopupMenu on the same right click too.

    You would probably add the standard listener for this sort of thing
    with the addition of selecting the item under the mouse.
    class PopupListener extends MouseAdapter {
        public void mousePressed(MouseEvent e) {
            maybeShowPopup(e);
        public void mouseReleased(MouseEvent e) {
            maybeShowPopup(e);
        private void maybeShowPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
                // Make selection
                JList list = (JList) e.getComponent();
                Point p = e.getPoint();
                int index = list.locationToIndex( p );
                if ( index != -1 ) {
                     Rectangle r = list.getCellBounds( index, index );
                     if ( r.x <= p.x && p.x <= r.x + r.width &&
                          r.y <= p.y && p.y <= r.y + r.height )
                         list.setSelectedIndex( index );
                // show popup
                popup.show(e.getComponent(),
                           e.getX(), e.getY());
    }If you want more advanced selection capabalities with the right click,
    I'd look at implementing your own MouseInputHandler which checks for
    isMouseLeftButton() || isPopupTrigger(); see BasicListUI.MouseInputHandler.

  • Slow Selection in JList

    Hi all,
    I have a JList with about 10,000 entries. Manual selection of elements and of chunks with elements is no problem. However, if I use JList.addSelectionInterval() for about 500 chunks, it takes about three minutes. The first few calls return immediately but than each call to JList.addSelectionInterval() takes longer and longer (about 1sec per call in the end).
    Any ideas how to speed up this? Or is it a "well-known" limitation in JList?
    Thanks in advance, Craud

    Never seen the problem.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the posted code retains its original formatting.

  • Permeantly select a JList Item.

    how would i permeantly select a item in a Jlist? ie. Even if the user clicks it it wont uncheck, it will always be selected.
    There will be other items in the Jlist which they may select and deselect but one which they cannot and stays selected.
    Thanks

    Hi,
    I would use the CellRenderer since selection if just the renderer drawing it. The example below should demonstrate what I mean.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class PermCellRenderer extends JLabel implements ListCellRenderer
      private int[] permIndices;
      public PermCellRenderer()
        this( null );
      public PermCellRenderer( int[] permIndices )
        setOpaque( true );
        this.permIndices = permIndices;
        System.out.println( this.permIndices[0] );
      private boolean isPermanent( int index )
        boolean outVal = false;
        if( permIndices != null )
          for( int i = 0; i < permIndices.length; ++i )
            if( permIndices[i] == index )
              outVal = true;
              break;
        return( outVal );
      public Component getListCellRendererComponent( JList list, Object value,
                                                     int index,
                                                     boolean isSelected,
                                                     boolean cellHasFocus )
        setText( value.toString() );
        if( isPermanent( index ) || isSelected )
          setBackground( list.getSelectionBackground() );
          setForeground( list.getSelectionForeground() );
        else
          setBackground( list.getBackground() );
          setForeground( list.getForeground() );
        return( this );
    public class PermListExample extends JFrame
      JList list;
      public PermListExample()
        super( "Permanent List Selection" );
        String[] data = { "First", "Second", "Permanent", "Fourth", "Fifth" };
        int[] perm = { 2 };
        list = new JList( data );
        list.setCellRenderer( new PermCellRenderer( perm ) );
        list.setVisibleRowCount( 10 );
        getContentPane().add( list );
        pack();
      public static void main(String[] args)
        new PermListExample().setVisible( true );
    }Enjoy,
    Manfred.

  • Remove Selection from jList ??

    Hi,
    How do I remove a Selection from a jList??
    The items in the jList are Vectors
    I now use jList.clearSelection() but the selection stays there..
    Thanks,
    Marie

    Funny you should ask. I just now decided to try out what I suggested because I've never actually used a Vector in a JList. In my simple example below, I actually have to call repaint on the list to get it to refresh. I should NOT have to do that. Might be a bug in the VM?Please try it out on your machine and see if you can remove the 'repaint' statement in my action listener and get the list to refresh.
    I use 1.4.1_02 JDK. Let me know also which JDK you're using. Thanks!
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.util.Vector;
    public class MyList extends JFrame {
         Vector model = new Vector();
         public MyList() {
              super();
              setSize(300,400);
              getContentPane().setLayout(new BorderLayout());
              buildModel();
              final JList list = new JList(model);
              getContentPane().add(list, BorderLayout.CENTER);
              JButton btn = new JButton("remove");
              btn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        model.remove(list.getSelectedIndex());
                        list.repaint(); //why should I have to force a repaint???
              getContentPane().add(btn, BorderLayout.NORTH);
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              show();
         private void buildModel() {
              model.add("one");
              model.add("two");
              model.add("three");
         public static void main(String[] args) {
              new MyList();

Maybe you are looking for