Scroll JList with Selection

When I use setSelectedIndex(...) the selected item is accurately chosen, but I want the selection item to automatically be scrolled to if it is off the window.
If this makes it easier, the item is gaurunteed to be either one item too high or too low.

Whenever I am in your situation, the first thing I do is to see if I can find something in the documentation. And sure enough, browsing through the JList API
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JList.html
you'll find the method
ensureIndexIsVisible(int index)
which seems to be doing what you want.

Similar Messages

  • 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.

  • Synchronize JList with JScrollPane

    hi all,
    I want to automatically move the scroll in the JScrollPane when I change the selected position in the JList with setSelectedIndex, right now the list is correctly selected, but the scroll remains on the top, how could I move it to position the list to see the selected item?
    thanks!
    mykro

    JComponent has a scrollRectToVisible method you could use along with JList's getCellBounds method. Maybe register a ListSelectionListener with the list, then in valueChanged get the newly selected cell's bounds from getCellBounds and call scrollRectToVisible on the JList with the cell bounds.

  • Key pressed in Jlist and selecting the item of key list accordingly

    Hi,
    I have a JList with the items in sorted order.Now I want that if a person presses any key (say K) then the first item starting with K should be selected.Hmmm I can do it by addding a key listener to the list and cheking all the items in the list ,by traversing through the whole lenght of JList and selecting the item if it starts with the character of the key pressed.
    But i was thinking if there is any better way to do that?
    Regards Amin

    see bugid: 4654916 - it does say that the the
    scrolling for the JList should now work with keyboard
    selection.I have the same problem. Thanx for the hint with the bugid. Saw a good workaround there with a simple subclass of JList. Works for me although it is annoying to subclass JList all the time. The bug seems not to be fixed in the 1.4.1 JDK.
    Andreas

  • DND from a JList with a single gesture

    I am writing an application that allows users to drag an item from a JList in one JInternalFrame to a JList in another. The users are complaining that "sometimes it works and sometimes it doesn't". I'm using JDK 1.4.2_02.
    As an example of the required behavior, imagine using the Windows Explorer to move a file from one directory to another. You do not have to click once on a file name to select it and click again to start the drag operation; you just click once and start dragging, whether the file was "selected" or not.
    However, when you try to drag from a JList, the gesture works only if the item you click on is already selected. Otherwise you have to click once on the item to select it and click again to start dragging. For most applications (for instance a word processor) you would expect this behavior, but for this application it is confusing and unacceptable. You feel like you're using a vaccuum cleaner that doesn't always pick up the dirt.
    The reason for the behavior can be found in the platform-dependent Swing code, in either com/sun/java/swing/plaf/gtk/SynthListUI.java or javax/swing/plaf/basic/BasicTextUI.java:
        private static final ListDragGestureRecognizer defaultDragRecognizer = new ListDragGestureRecognizer();
         * Drag gesture recognizer for JList components
        static class ListDragGestureRecognizer extends BasicDragGestureRecognizer {
          * Determines if the following are true:
          * <ul>
          * <li>the press event is located over a selection
          * <li>the dragEnabled property is true
          * <li>A TranferHandler is installed
          * </ul>
          * <p>
          * This is implemented to perform the superclass behavior
          * followed by a check if the dragEnabled
          * property is set and if the location picked is selected.
            protected boolean isDragPossible(MouseEvent e) {
             if (super.isDragPossible(e)) {
              JList list = (JList) this.getComponent(e);
              if (list.getDragEnabled()) {
                  ListUI ui = list.getUI();
                  int row = ui.locationToIndex(list, new Point(e.getX(),e.getY()));
                  if ((row != -1) && list.isSelectedIndex(row)) {
                   return true;
             return false;
        }Note that the method returns true only if the row is already selected.
    How can I fix this? The obvious method is to substitute my own version of ListDragGestureRecognizer, but that's an unsafe hack. BasicDragGestureRecognizer is not available to the application programmer and is potentially different for every platform and for different versions of the JVM. It's not "documented" that I know of, so there's no way to guarantee my own version is compatible.
    Mark Lutton

    First, see http://developer.java.sun.com/developer/bugParade/bugs/4521075.html
    There are two approaches there that worked for me: simon's and scmorr's. I prefer Simon's, but here is the code for both:
    1) based on scmorr's comments:
       private void fixListMouseListeners()
          MouseListener[] allMouseListeners = getMouseListeners();
          String listenerName = "javax.swing.plaf.basic.BasicListUI$ListDragGestureRecognizer";
          MouseListener listDragGestureRecognizer = null;
          // find the drag gesture listener we are looking for and remove it from
          // mouse listeners
          for (int i = 0; i < allMouseListeners.length; ++i)
             MouseListener currentListener = allMouseListeners[ i ];
             String currentListenerClassName = currentListener.getClass().getName();
             if (currentListenerClassName.equals(listenerName))
                listDragGestureRecognizer = currentListener;
                removeMouseListener(listDragGestureRecognizer);
                break;
          // add drag gesture listener back in at the end -- this allows the
          // mouse input handler (which does selection) to run first
          if (listDragGestureRecognizer != null)
             addMouseListener(listDragGestureRecognizer);
       }  // fixListMouseListeners()2) simon's approach:
       // the cached selection event
       private MouseEvent myCachedEvent;
        * overriding this so we can select and drag at same time
        * @param firstIndex is first interval index
        * @param lastIndex is last interval index
        * @param isAdjusting is whether event is an adjusting event
       protected void fireSelectionValueChanged(int firstIndex,
                                                int lastIndex,
                                                boolean isAdjusting)
          // now continue with update of whoever is listening to list for selection changes
          super.fireSelectionValueChanged(firstIndex, lastIndex, isAdjusting);
          // if the selection occurred and we have cached the event,
          // launch a copy of the cached event so dragging can occur right
          // away, if necessary
          if (myCachedEvent != null)
             super.processMouseEvent(new MouseEvent(               
                   (Component) myCachedEvent.getSource(),
                   myCachedEvent.getID(),     
                   myCachedEvent.getWhen(),     
                   myCachedEvent.getModifiersEx(),     
                   myCachedEvent.getX(),     
                   myCachedEvent.getY(),     
                   myCachedEvent.getClickCount(),     
                   myCachedEvent.isPopupTrigger()));
             myCachedEvent= null;
       }  // fireSelectionValueChanged()
        * overriding so we can cache the mouse event
        * @param e is the invoking event
       protected void processMouseEvent(MouseEvent e)
          int modifiers = e.getModifiersEx();
          // if clicked with left button, cache the event
          if ((modifiers & e.BUTTON1_DOWN_MASK) != 0)
             myCachedEvent = e;
          // go ahead and do normal processing on event
          super.processMouseEvent(e);
       }  // processMouseEvent()This does the job, but I had further requirements that required a bit more intervention. I am working with dragging an item between 2 JLists (single selection mode), and I am also trying to enforce that only one of my 2 lists can have a selection at any given time, using a ListSelectionListener, paying attention to events only if getValueIsAdjusting() is true.
    The problem comes if you abort a drag and then select an item in the other list that you weren't dragging from. When you drag, the list you drag from doesn't get a setValueIsAdjusting(false) since you don't get the mouseReleased() from MouseInputHandler, and leaving the list in "isAdjusting == true"-mode when a drag is aborted makes my selection stuff not work.
    My solution was to explictly call comp.setValueIsAdjusting(false) in my exportDone() function of my custom TransferHandler. Now everything is cool.

  • Mavericks Mail-cannot scroll down to select a group by holding mouse button.

    I do not like the new Mavericks mail. When I attempt to hold the left mouse button and scroll down to select a group, the program automatically locks onto the first message I touch and moves it. Prior to Mavericks scrolling was an easy process. This new mail is very clumsy and I have to select one message, then hold shift key, then selelct the last message in the group. ....Clumsy and slow.
    Does anyone know a workaround for this? The tutorials don't address it and the "What's new in Mail?" file doesn't either.  If there is not a workaround, is there a way to disable the Mavericks configuration in Mail and go back to regular mail? I'd appreciate any tips or help on  this.

    Okay, I tried deleting the Finder preferences first (along with a handful of other preference files that I knew were no longer needed), and it seemed to help--at first. But eventually, all the same problems started happening again, so I concluded that it was necessary to just start with a fresh (empty) preferences folder. As you know, this is a pain to deal with, but I limited my pain by moving all the old preferences files into a folder on the Desktop rather than simply deleting them. That way, I could just put back any missing preferences that were too hard to recreate. Restoring all of my preferences with new (uncorrupted) prefs files will be an ongoing process, but the good news is that this effort (so far) seems to have solved the problem. Mail is responding to all my clicks, even when I switch between different apps and different spaces.  :-)
    Now that things are working correctly, I notice that when I switch between apps and/or spaces, the selected app (or the frontmost app in the new space) will show an active state for its window, whereas before, the selected app didn't update to show that it was active--it kept the inactive state for its window. I'm no expert, but it seems to me that this might have something to do with the windowserver process, so it might make sense for the next person who stumbles on this thread to start by deleting any preferences files that begin with com.apple.windowserver. Just a hunch, but it's worth starting there before you do a complete flush of all your preferences.
    Thanks again for the help--hopefully this workaround will be persistent. Fingers crossed!

  • Populatin a JList with elements from a DB (access here)

    last year i was able to populate a JList with data from a database
    however this year something doesnt work
    this is last year
    public String[] getOnderwerpen()
    System.out.println(theConnection==null?" connection null ":" connection niet null ");
    String []locaties = new String[30];
    ArrayList returnLijst;
    returnLijst = new ArrayList();
    ArrayList arraylist;
    arraylist = new ArrayList();
              String[] deLocaties = null;
    try{
    String onderwerpQuery = "SELECT OnderwerpID FROM Onderwerp order by OnderwerpID";
    Statement statement = theConnection.createStatement();
    System.out.println(statement==null?" statement null ":" statement niet null ");
    statement.execute(onderwerpQuery);
    ResultSet result = statement.getResultSet();
    System.out.println(result==null?" ResultSet null ":" ResultSet niet null ");
    int i = 0;
                   while(result.next())
              //          locaties[i] = result.getString("OnderwerpID");
    locaties[i] = result.getString("OnderwerpID");
                                            i++;
    deLocaties = new String;
              for (int j=0;j<deLocaties.length;j++)
                   deLocaties[j] = locaties[j];
              sorteerStringArray(deLocaties);
    }//end-try
    catch (Exception e) {
    e.printStackTrace();
    return deLocaties;
    & this is what i did this year
    public String[] getbedrijfNaam()
              String[] bedrijfsNamen = new String[Constanten.aantalBedrijven];
              String[] deBedrijfsNamen = null;
         System.out.println(theConnection==null?" connection null ":" connection niet null ");
         System.out.println("test this");
         try{
         String onderwerpQuery = "SELECT naam FROM organisatie";
         Statement statement = theConnection.createStatement();
         System.out.println(statement==null?" statement null ":" statement niet null ");
         statement.execute(onderwerpQuery);
         ResultSet result = statement.getResultSet();
         int i = 0;
                        while(result.next())
                             bedrijfsNamen[i] = result.getString();
                                                 i++;
                        deBedrijfsNamen = new String[i];
                   for (int j=0;j<deBedrijfsNamen.length;j++)
                        deBedrijfsNamen[j] = bedrijfsNamen[j];
                   sorteerStringArray(deBedrijfsNamen);
                   statement.close();
                   //theConnection.close();
         }//end-try
         catch (Exception e) {
         e.printStackTrace();
         return deBedrijfsNamen;
    is there something here thats not right
    or does this no longer work because of the changes made in 1.5

    last year i was able to populate a JList with data from a database
    however this year something doesnt work
    this is last year
    public String[] getOnderwerpen()
    System.out.println(theConnection==null?" connection null ":" connection niet null ");
    String []locaties = new String[30];
    ArrayList returnLijst;
    returnLijst = new ArrayList();
    ArrayList arraylist;
    arraylist = new ArrayList();
              String[] deLocaties = null;
    try{
    String onderwerpQuery = "SELECT OnderwerpID FROM Onderwerp order by OnderwerpID";
    Statement statement = theConnection.createStatement();
    System.out.println(statement==null?" statement null ":" statement niet null ");
    statement.execute(onderwerpQuery);
    ResultSet result = statement.getResultSet();
    System.out.println(result==null?" ResultSet null ":" ResultSet niet null ");
    int i = 0;
                   while(result.next())
              //          locaties[i] = result.getString("OnderwerpID");
    locaties[i] = result.getString("OnderwerpID");
                                            i++;
    deLocaties = new String;
              for (int j=0;j<deLocaties.length;j++)
                   deLocaties[j] = locaties[j];
              sorteerStringArray(deLocaties);
    }//end-try
    catch (Exception e) {
    e.printStackTrace();
    return deLocaties;
    & this is what i did this year
    public String[] getbedrijfNaam()
              String[] bedrijfsNamen = new String[Constanten.aantalBedrijven];
              String[] deBedrijfsNamen = null;
         System.out.println(theConnection==null?" connection null ":" connection niet null ");
         System.out.println("test this");
         try{
         String onderwerpQuery = "SELECT naam FROM organisatie";
         Statement statement = theConnection.createStatement();
         System.out.println(statement==null?" statement null ":" statement niet null ");
         statement.execute(onderwerpQuery);
         ResultSet result = statement.getResultSet();
         int i = 0;
                        while(result.next())
                             bedrijfsNamen[i] = result.getString();
                                                 i++;
                        deBedrijfsNamen = new String[i];
                   for (int j=0;j<deBedrijfsNamen.length;j++)
                        deBedrijfsNamen[j] = bedrijfsNamen[j];
                   sorteerStringArray(deBedrijfsNamen);
                   statement.close();
                   //theConnection.close();
         }//end-try
         catch (Exception e) {
         e.printStackTrace();
         return deBedrijfsNamen;
    is there something here thats not right
    or does this no longer work because of the changes made in 1.5

  • By default a item in a JList should selected

    Hi
    I need a item in the JList should be selected(not the first item) by default while I am creating a new instances for the JList.
    Note: I am rendering a button in the JList.
    with regrads
    senthil kumar

    You should be able to use either of the following methods of JList: setSelectedIndex(defaultIndex); or setSelectedValue(defaultObject, shouldScroll);Is one of these what you are looking for?

  • Traversing JList with arrow keys

    I've got a small problem when i try to traverse a JList with the arrow keys. When I'm at the first index of the list and press the UP arrow, I want to select the last index of the list.
    switch (keyCode){
            case VK_UP:
                    if(list.isSelectedIndex(list.getFirstVisibleIndex()))
                        list.setSelectedIndex(list.getLastVisibleIndex());
                    break;
    }When I use this code, the program selects the second last index (not the last). How can I fix this problem?
    Any suggestions will be appreciated.

    I found this thread useful but ultimately solved this another way using key binds. Maybe someone will find this useful.
    public MyDialogConstructor() {
        bindKeys();
    private void bindKeys() {
              InputMap inputMap = getJList().getInputMap(JComponent.WHEN_FOCUSED);
              KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
              inputMap.put(key, "jlist:UP");
              getJList().getActionMap().put("jlist:UP", new AbstractAction() {
                   private static final long serialVersionUID = 1L;
                   public void actionPerformed(ActionEvent e) {
                        if (getJList().isSelectedIndex(getJList().getFirstVisibleIndex())) {
                             getJList().setSelectedIndex(getJList().getLastVisibleIndex());
                        } else {
                             getJList().setSelectedIndex(getJList().getSelectedIndex() - 1);
              key = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
              inputMap.put(key, "jlist:DOWN");
              getJList().getActionMap().put("jlist:DOWN", new AbstractAction() {
                   private static final long serialVersionUID = 1L;
                   public void actionPerformed(ActionEvent e) {
                        if (getJList().isSelectedIndex(getJList().getLastVisibleIndex())) {
                             getJList().setSelectedIndex(getJList().getFirstVisibleIndex());
                        } else {
                             getJList().setSelectedIndex(getJList().getSelectedIndex() + 1);
         }

  • Problems scrolling - keep accidentally selecting things

    New Touch user, long-time iPod user - and this is driving me nuts. When I attempt to scroll through (either slowly or "flicking") lists of songs or artists I nearly always end up with something selected the 3rd or 4th time I move my finger on the screen. I've tried a light touch, hard touch, different parts of the screen - It sometimes takes me 10 tries or more to get to ONE artist (and then several more to get to what song I want). Sometimes instead of selecting I get a "delete" box! I almost hit it accidentally going through the endless repetitive motions of trying to get to what I wanted. I'm at work now and can't check - but it looks like a couple of my playlists are not on the iPod either.
    I've run a dozen searches and come up with nothing. Is there some trick to scrolling with the touch screen that I just don't get?
    And - when it's in the "sideways" position, is there some way to get the "back" arrow or the categories on the screen? I'm trying to keep it mounted in my car, but it seems like I have to remove it and change the orientation to do different things. I can't find anything in the manual on that one either, and that inconsistency makes it useless when driving.
    Help!

    About the "soft" or "hard" touch. I sorta use the side of my thumbs (big thumbs) and try to keep to a "medium" touch with a pretty long flick (it covers probably half the screen). I wasn't able to duplicate a problem with selecting something by touching lightly. Then again, I also have a protective screen, so it could be damping some of the effects.
    In any case, the horizontal position I also find a little bit pointless, as all it shows (and all I have ever been able to get it to show) is the cover flow when in the music selection. So I think the answer to that is no, you can't get the back arrow in the landscape/horizontal/sideways position.
    I don't know what might be going on with the playlists: not selecting them for update, not having songs playable by an ipod in them, or not enough space are the first ones that come to mind.
    Tomek

  • JList with LineBorder think=2

    hello all
    i am writing a look and feel .
    and when i have a JList with LineBorder with thinness = 2 and a item is selected ,
    i cant see the complete text of the selected item
    my question is there a simple way to make this work
    without changing the list preferred size inside my application ?
    thank you
    here is an example
    (please select the third item 'ccccccccccccccc')
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.border.LineBorder;
    public class DialogTest extends JDialog{
      public DialogTest(JFrame f){
        super(f);
        JList list = new JList(new String[]{"aaaaaaaaaaaa" ,"bbbbbbbbbbbbbbb" ,"cccccccccccccccccc"});
        list.setCellRenderer(new DefaultListCellRenderer(){
          public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            if(isSelected){
              setBorder(new LineBorder(Color.GREEN ,2));
            }else{
              setBorder(null);
            setText(value.toString());
            return this;
        setLayout(new BorderLayout());
        add(new JScrollPane(list) ,BorderLayout.CENTER);
        pack();
      public static void main(String[] args){
        DialogTest t = new DialogTest(new JFrame());
        t.setVisible(true);
    }

    ok, thanks now this works on the demo also for me.
    but when settings my UI ,i get same result
    i want this border no mater what Render the user will put
    this is what i do
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.ComponentOrientation;
    import java.awt.Graphics;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.JComponent;
    import javax.swing.JList;
    import javax.swing.ListCellRenderer;
    import javax.swing.ListModel;
    import javax.swing.ListSelectionModel;
    import javax.swing.border.CompoundBorder;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.LineBorder;
    import javax.swing.plaf.ComponentUI;
    import javax.swing.plaf.basic.BasicListUI;
    import org.jtpc.gui.borders.RoundBorder;
    import org.jtpc.gui.defaultTheme.FocusBorderHandler;
    import org.jtpc.utils.JTPCThemeManager;
    public class JTPCListUI extends BasicListUI{
      public void installUI(JComponent c){
        super.installUI(c);
        if(c instanceof JList){
          JList listJtpc = (JList)c;
          listJtpc.setCellRenderer(new JTPCListCellRenderer());
      public static ComponentUI createUI(JComponent c) {
        return new JTPCListUI();
      LineBorder m_borderSelected     = new LineBorder (Color.GREEN ,3);
      EmptyBorder m_borderDeselected  = new EmptyBorder(new Insets(3, 3, 3, 3));
       * COPY PASTE CODE FROM PARENT 'BasicListUI' ,IN JAVA VERSION  jdk1.6.0_18
       * Paint one List cell: compute the relevant state, get the "rubber stamp"
       * cell renderer component, and then use the CellRendererPane to paint it.
       * Subclasses may want to override this method rather than paint().
       * @see #paint
      protected void paintCell(
          Graphics g,
          int row,
          Rectangle rowBounds,
          ListCellRenderer cellRenderer,
          ListModel dataModel,
          ListSelectionModel selModel,
          int leadIndex)
        Object value = dataModel.getElementAt(row);
        boolean cellHasFocus = list.hasFocus() && (row == leadIndex);
        boolean isSelected = selModel.isSelectedIndex(row);
        Component rendererComponent = cellRenderer.getListCellRendererComponent(list, value, row, isSelected, cellHasFocus);
        FocusBorderHandler h = new FocusBorderHandler();
        if(isSelected){
          ((JComponent)rendererComponent).setBorder(m_borderSelected);
        }else{
          ((JComponent)rendererComponent).setBorder(m_borderDeselected);
        int cx = rowBounds.x;
        int cy = rowBounds.y;
        int cw = rowBounds.width;
        int ch = rowBounds.height;
        boolean isFileList = Boolean.TRUE.equals(list.getClientProperty("List.isFileList"));
        if (isFileList) {
          // Shrink renderer to preferred size. This is mostly used on Windows
          // where selection is only shown around the file name, instead of
          // across the whole list cell.
          int w = Math.min(cw, rendererComponent.getPreferredSize().width + 4);
          if (!(list.getComponentOrientation() == ComponentOrientation.LEFT_TO_RIGHT)) {
            cx += (cw - w);
          cw = w;
        rendererPane.paintComponent(g, rendererComponent, list, cx, cy, cw, ch, true);
      class JTPCListCellRenderer extends DefaultListCellRenderer {
        public  Component   getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
          setText(value.toString());
          return this;
    }Edited by: shay_te on 17:34 15/05/2010

  • JList with no deselection allowed?

    Can I hav a JList (SINGLE_SELECTION selection mode). wherein the user is not allowed to deselect but only change the selection to another item????
    Is there a propery with the JList or its selection model that I can make use of??

    How about just resetting it?import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Test2 extends JFrame {
      JList jl = new JList(new String[] {"One","Two","Three","Four","Five","Six"});
      boolean inEvent=false;
      public Test2() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        content.add(new JScrollPane(jl), BorderLayout.CENTER);
        jl.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jl.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
          public void valueChanged(ListSelectionEvent lse) {
            if (inEvent || lse.getValueIsAdjusting()) return;
            inEvent=true;
            if (jl.getSelectedIndex()==-1) jl.setSelectedIndex(lse.getFirstIndex());
            inEvent=false;
        setSize(300,300);
      public static void main(String[] args) { new Test2().setVisible(true); }
    }

  • JList with Checkboxes

    For my application, I require a JList with each row containing a text label, and two check boxes which can be checked or unchecked in the list. I have written the code below to render list elements in this way, however the checkboxes cannot be checked in the list. Is there something else that I have to do to enable this?
    Code:
    public class NodeListCellRenderer implements ListCellRenderer {
          * @see javax.swing.ListCellRenderer#getListCellRendererComponent(javax.swing.JList,
          *      java.lang.Object, int, boolean, boolean)
         public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                   boolean cellHasFocus) {
              //Convert Value to node
              final Node n=(Node)value;
              //Create JPanel object to hold list element
              JPanel listElement=new JPanel();
              listElement.setLayout(new GridLayout(1,3));
              //Create Label to hold node name
              JLabel nodeName=new JLabel(n.toString());
              //Create checkbox to control trace
              final JCheckBox traceBox=new JCheckBox("Trace",n.isTraceEnabled());
              //Add Event Listener
              traceBox.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        n.setTrace(traceBox.isSelected());
              //Create Checkbox to control
              final JCheckBox failedBox=new JCheckBox("Failed",n.hasFailed());
              //Add Event Listener
              failedBox.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        n.setFailed(failedBox.isSelected());
              //Colour All Components Grey if Selected
              if (isSelected) {
                   nodeName.setBackground(Color.LIGHT_GRAY);
                   failedBox.setBackground(Color.LIGHT_GRAY);
                   traceBox.setBackground(Color.LIGHT_GRAY);
                   listElement.setBackground(Color.LIGHT_GRAY);
              //Build List Element
              listElement.add(nodeName);
              listElement.add(traceBox);
              listElement.add(failedBox);
              return listElement;
    }

    Thanks for the pointer to that. I have created a mouse listener for my list, which in a very crude way is able to set the checkbox values on a list click, by changing the underlying objects that are stored in the list.
    The problem that I'm having now is that if I click a checkbox in the currently selected list element, the value in the underlying object is set immediately, but the Checkbox does not update until i select another element in the list.
    This seems to indicate that the getListCellRendererComponent method is not called when you click on the currently selected list element. Is there any way round this?
    Here's my current mouse listener code:
    list.addMouseListener(new MouseAdapter() {
                   public void mousePressed(MouseEvent e) {
                        //get index of element clicked
                        int index=list.locationToIndex(e.getPoint());
                        //Get Element at Index
                        Node n=(Node)list.getModel().getElementAt(index);
                        /*Work out X position, if 33-66% of width, "trace" checkbox clicked
                        otherwise if >66% of width, "failed" checkbox clicked*/
                        if (e.getX()>(list.getWidth()*0.33) && (e.getX()<list.getWidth()*0.66)) {
                             n.setTrace(!n.isTraceEnabled());
                             list.revalidate();
                        } else if (e.getX()>(list.getWidth()*0.33)) {
                             n.setFailed(!n.hasFailed());
                             list.revalidate();
              });

  • JList with ImageIcon

    Hello,
    Can I have JList with an ImageIcon beside it?e.g
    "imageicon" "sometext"
    code snippet would be helpful.
    Thanks

    Hello,
    little improvement-update, custom ListCellRenderer now checks whether object is a String only or a JLabel with an ImageImage. You can use it for both versions of JLists.
    import javax.swing.*;
    import java.awt.*;
    public class ImageTextList extends JFrame
         private static String[]text = new String[10];
         private static JLabel[]labels = new JLabel[text.length];
         private static ImageIcon[] icons = new ImageIcon[labels.length];
         static
              for(int i=0; i<text.length; i++)
                   text[i]   = "Images " + (i+1);
                   icons[i]  = new ImageIcon(     "../testproject/img/" + (i+1) + ".jpg");
                   labels[i] = new JLabel(text, icons[i], JLabel.CENTER);
         public static void main(String[] args)
              new ImageTextList();
         public ImageTextList()
              super("Image+Text in a JList");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //test with labels and text
              JList list = new JList(labels);
              list.setCellRenderer(new MyCellRenderer());
              getContentPane().add(new JScrollPane(list));
              pack();
              setLocationRelativeTo(null);
              setVisible(true);
         class MyCellRenderer extends JLabel implements ListCellRenderer
              private JLabel label = null;
              // This is the only method defined by ListCellRenderer.
              // We just reconfigure the JLabel each time we're called.
              public Component getListCellRendererComponent(
                   JList list,
                   Object value,
              // value to display
              int index, // cell index
              boolean isSelected, // is the cell selected
              boolean cellHasFocus) // the list and the cell have the focus
                   String s = value.toString();
                   ImageIcon icon = null;
                   //checks whether the source is a label or another object(String only)
                   if(value instanceof JLabel)
                   {System.out.println("label");
                        label = (JLabel)value;
                        icon = (ImageIcon)label.getIcon();
                        s = label.getText();
                   setText(s);
                   setIcon(icon);
                   if (isSelected)
                        setBackground(list.getSelectionBackground());
                        setForeground(list.getSelectionForeground());
                   } else
                        setBackground(list.getBackground());
                        setForeground(list.getForeground());
                   setEnabled(list.isEnabled());
                   setFont(list.getFont());
                   setOpaque(true);
                   return this;
    regards
    Tim

  • Problem with "SELECT...FOR UPDATE OF..." and "POST command" combination

    Problem with "SELECT...FOR UPDATE OF..." and "POST command" combination
    Problem in committing transactions in Multiple Forms (Oracle Forms) with POST built-in command:
    Consider that the following statements are written in WHEN-WINDOW-CLOSED trigger of a called form.
    Statements in called form (Form name: FORM_CHILD):
    go_block('display_block') ;
    do_key('execute_query') ;
    -- Data from table_b will be populated in this block, based on the value of COLUMN_1 obtained
    -- from TABLE_A.
    -- Example: If the value of COLUMN_1 is 10, then all the matching records from TABLE_B, which
    -- are inserted with value 10 in TABLE_B.COLUMN_1 will be fetched and shown here.
    if user_choice = 'YES' then
    commit ;
    else
    rollback ;
    end if ;
    Statements in calling forms:
    There are two calling forms having following statements and it is going to call the above said called form.
    CALLING FORM 1
    Statements in KEY-COMMIT trigger:
    post;
    call_form(form_child, no_activate) ;
    Statements in ON-INSERT trigger:
    select column_1
    from table_a
    for update of column_1
    where column_2 = 'X' ;
    update table_a
    set column_1 = column_1 + 1
    where column_2 = 'X' ;
    insert into table_b ...;
    insert into table_b ...; Statements in KEY-COMMIT trigger:
    post;
    call_form(form_child, no_activate) ;
    CALLING FORM 2:
    Statements in ON-INSERT trigger:
    select column_1
    from table_a
    for update of column_1
    where column_2 = 'X' ;
    update table_a
    set column_1 = column_1 + 1
    where column_2 = 'X' ;
    insert into table_b ...;
    insert into table_b ...;
    insert into table_b ...;
    Our understanding:
    Assume that both the forms are running from two different machines/instances, issuing commit at the same time. In this case, forms will start executing the statements written in ON-INSERT trigger, the moment POST command is executed. Though the commit is issued at the same time, according to oracle, only one of the request will be taken for processing first. Assume that calling form 1 is getting processed first.
    So, it fetches the value available in COLUMN_1 of TABLE_A and locks the row from further select, update, etc. as SELECT...FOR UPDATE command is used (note that NOWAIT is not given, hence the lock will be released only when COMMIT or ROLLBACK happens) and proceed executing further INSERT statements. Because of the lock provided by the SELECT...FOR UPDATE command, the statements in calling form 2 will wait for the resource.
    After executing the INSERT statements, the FORM_CHILD is called. The rows inserted in to TABLE_A will be queried and shown. The database changes will be committed when user closes the window (as COMMIT is issued in its WHEN-WINDOW-CLOSED trigger). Then the SELECT...FOR UPDATE lock will be released and calling form 2's statements will be executed.
    Actual happenings or Mis-behavior:
    Calling form 2 starts executing INSERT statements instead of waiting for SELECT...FOR UPDATE lock. Also, the value selected from TABLE_A.COLUMN_1 is same in both the calling forms, which is wrong.
    The rows inserted into TABLE_B are having similar COLUMN_1 values in calling form 2 and they are fetched and shown in the called form FORM_CHILD.
    Note that in calling form 2 also POST only is issued, but the changes posted there are accessible in calling form 1 also, which is wrong.
    Kindly suggest us as to how to fix above problem. It will be much use, if you can send us the information regarding the behavior of Oracle Forms POST built-in also.
    Our mail ID: [email protected]
    Thanks a lot in advance.

    You have several problems:
    1. On-Insert will ONLY run if you have created a new record in a base-table block. If you haven't done that, then the POST command will not cause it to run.
    2. Select for update without a "no wait" will lock records for the first form, but when the second form tries this, it will hit the ORA-00054 exception, and will NOT wait. The only way you could make it wait is to issue an UPDATE sql command, which is not such a good way to go.
    All POST does is issues SQL insert or update commands for any changes the user has made to records in a form's base-table blocks, without following with a Commit command.
    Also understand that Commit is the same as Commit_Form, and Rollback is the same as Clear_Form. You should read up on these in the Forms help topics.

Maybe you are looking for

  • Server 2012 R2 - WSUS - Win 7 reporting status, Win 8 not

    Hi, We have WSUS running in Server 2012 R2 standard. I have a handful of Win 7 PCs reporting status successfully. All other Win 7 and Win 8/8.1 have "not yet reported". Looked at the windowsupdate.txt to compare a Win 7 working PC to a Win 8.1 non-wo

  • How to change the domain name

    Our company was bought in an acquisition and for a long time we kept out domain and firewall. Now, we have to move the servers physically and on the new domain. All Oracle servers have been installed with the service of ORANAME.usdv.sdv.com and the T

  • My speakers crackle out for a few seconds

    Hi i have a macbook pro retina 15 inch mid-2012, my speakers occasionally fizzle out for a few seconds and then return to normal. Do you know what this could be?

  • GPS, WLAN+3G

    So, I have an iPad, the model with the 3G. I have been using it effectively as a GPS all over the world, even in places that I don't have 3G connection (which is only for the US's AT&T). I've been using it in the US, India and Israel (to name a few p

  • Output Detrminatio

    My requirement is to create a IDOC and send it to XI system when a delivery is created in SAP system. I want to use Output determination for this requirement The following are the steps I've configured Can someone resolve the error message Im getting