Selecting jList items

Hi!
I'm developing a image browser app using JList. I'm having problems with a contextual popup menu. When I click on an image from the JList I show the popup with some options related to the image (delete,
paste, etc ...),
But when I click on an empty zone in the JList, the last item gets selected and the same popup gets shown even though I didn't click any item.
1) what should i do so that no item in the jlist is selected when i click in its empty zones
2) how do i make a different set of menuitems be enabled or disabled which i click on the empty zones
Thanks in adavance
kalpana

1) what should i do so that no item in the jlist is sselected when i click in its empty zonesYou may have to override JList's locationToIndex(Point p) method so that it returns -1 (or probably the currently selected index) when the point is not located in any of the list items. I believe by default, this selects the closets index to the point.
2) how do i make a different set of menuitems be enabled or disabled which i click on the empty zonesYou have to provide some sort of manager class or interface where the popup menu can go to obtain the state of the image in the list, and enable or disable the menuItems as necessary.
ICE

Similar Messages

  • Delete Selected JList Item on Pressing Delete Key

    Hi,
    I have to delete selected JList item ((in JFrame using java Swing) after pressing Delete key. Please provide me code for this.
    Thanks
    Nitin

    Again read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/list.html]How to Use Lists and [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings.
    Are you sensing a common theme here? Do some reading on your own. The tutorial has most of the information you need.

  • Select JList item on Mouse over Event

    Hoi All,
    I am trying to find a way to select the items in a JList when the mouse is moved over the item.
    Any help is appreciated
    Kind Regrads ,
    Werns

    Hey J�rg,
    I solvd the problem by using the following method:
      public void dragOver(DropTargetDragEvent dtde) {
                jListLocalLibrary.setSelectedIndex(jListLocalLibrary.locationToIndex(dtde.getLocation()));
            }What i'm doing is creating a digital library so the owner of a book kan move a book between shelves so you have one JList that shows books of a shelf and a nother JList that shows the available shelves the JList is not enabled to accomodate multiple selection thus the derection from which the JList is approcahed does not matter.
    If you need more info just drop me a reply and i'll be happy to share.

  • Selecting JList item with the spacebar

    i have a class that extends JList, and my JList is a list of checkboxes. I would like to move to a checkbox with the arrow keys, check a checkbox with the spacebar, or uncheck it if the spacebar is pressed again. it should only select/deselect the certain checkbox and have no effect on the others. is there a way to do this?
    thanks :)

    okay, i figured this out myself... not too hard :) if there is a more efficient way, let me know.
    addKeyListener(new KeyListener() {
                  public void keyPressed(KeyEvent e) {
                   if(e.getKeyCode() == KeyEvent.VK_SPACE){
                        int index = getLeadSelectionIndex();
                        if (index != -1) {
                                     JCheckBox checkbox = (JCheckBox)getModel().getElementAt(index);
                                     checkbox.setSelected(!checkbox.isSelected());
                                     checkbox.setBackground(checkbox.isSelected() ? getSelectionBackground() : Color.white);
                                     repaint();
                  public void keyReleased(KeyEvent e){}
                  public void keyTyped(KeyEvent e){}
            });

  • Double click for JList items selection

    I would like to select JList items only by double clicking on them. I can write a mouse listener for detecting double clicks by my own (and handle it afterwards), by please tell me how to turn the default behavior off (selecting items by clicking one time).
    Thanks in advance
    Marek

    I would like to select JList items only by double clicking on them. Well the standard is to select or highlight on a mouseClick or by using the arrow keys on the keyboard.
    Then once you have a selected item you can perform and Action on the item by double clicking or by using the enter key. Remember you should always be able to use either the keyboard or the mouse to perform any given function.
    This posting shows my solution for the above scenario:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=626866

  • Dynamically changing size of JList items?

    Hello!
    I'm working on an application which kind of revolves around a JList with a custom ListCellRenderer. Now, it all works rather good as it is, but I want the selected JList item to show more detailed information about the selected value, and thus I need it to be bigger then the not selected items. The thing is that no matter what I do I can't seem to make the JList adopt to the new size of the selected item, which results in only half of the stuff in the selected item being shown.
    Is there any way to do this it would be great! (I bet there is some really simple way which I have simply overlooked.)
    And, fyi: The component returned by getListCellRendererComponent is a JPanel which consists of three JLabels using a GridLayout. The selected component is generally the same, but with an extra row in the GridLayout.
    Any help/suggestions will be greatly appreceated!
    Yours, Jiddo.

    I have tried with a couple of different layout managers, and none of them (except for this one) seems to offer me the layout I need. Also, I have tried making it return different instances depending on if it is selected or not. The non-selected one has only one row in the layout while the selected has two. Here is a screenshot of how it looks:
    http://img211.imageshack.us/img211/2779/jlistes1.jpg
    Yours, Jiddo.

  • 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);
    }

  • 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

  • JList item selected is displayed twice. Please Assist

    Folks,
    I have this strange behaviour when I select an item from the JList.
    When I select the an item, it gets displayed twice.
    Can anyone tell me why this is being displayed twice?
    I am also checking the Java Sun Swing tutorials site..but no luck as yet.
    Attached is a short class.
    If you click on Black or Blue etc ,it gets displayed twice...
    public class JListDemo extends JFrame{
    private JList colorList;
    private Container c;
    private String colorNames[] = {"Black", "Blue","Red","Green","Yellow"};
    public JListDemo() {
    super("JList Demo");
    c = getContentPane();
    c.setLayout(new FlowLayout());
    /** Create a List */
    colorList = new JList(colorNames);
    colorList.setVisibleRowCount(3);
    colorList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    c.add(new JScrollPane(colorList));
    //** Set up Event Handler.
    colorList.addListSelectionListener(
    new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e)
    System.out.println(colorList.getSelectedValue());
    setSize(1000,550);
    show();
    public static void main(String[] args) {
    JListDemo JListDemo1 = new JListDemo();
    }

    in your ListSelectionListener you must check if the event is one of multiple change events. In your case you get one event when the mouse first selects an item and possible more when you move the cursor over the other entries. If you are only interested in the final selection check if e.getValueIsAdjusting() is false.
    // not interested in events if they are not final
    if (e.getValueIsAdjusting())
        return;
    // do what ever you want
    System.out.println(colorList.getSelectedValue());
    ...Hope this helps!

  • Programatically Select an Item in a JList

    Hi,
    I need to do this: Programmatically select an item in a JList.
    JList.selectItem(0) will select the item 0 in the model but it will NOT visually highlight the selected item in the list.
    Neither will ensureIndexIsVisible(0),
    I need to automatically select and item in a list (highlight that item as well)
    As if someone has clicked on that item with the mouse.. however they haven't you see, my program has done it, programatically.
    Please don't refer me to the beginners guide to java, or the API documentation, the answer is not there.
    Thanks

    Swing related questions should be posted in the Swing forum.
    Please don't refer me to the beginners guide to java, or the API documentation, the answer is not there.Yes it is.
    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.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the 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.

  • JList item selection

    I am using a JList, and I would like to select certain items in the list. Right now I am doing it by passing the constructor an array of int indecies that correspond to the items I want selected.
    What I would really like to do, is have one item selected in red and the others selected the way they are. Or the other way around. I just want different color selections. I'm pretty sure I can not do this, but I just wanted to see if you guys (and gals) had any ideas.
    The other idea I had was to use a JPanel, and then use drawString to list the items, then capture the mouse click, find what item was selected, and then paint that rectangle the color I want.

    Hi
    You need to write a custom ListCellRenderer and set that for the list using: list.setCellRenderer(someCellRenderer); Once you have done that, populate the list with items (i.e. instances of a class which you created) that define whether the list item being drawn should be drawn using a red foreground. The renderer will need to check and see if the list item boolean value for painting in red is true, and if so set the foreground to red, otherwise use the default foreground color.
    Sorry if this sounds cryptic but I can't devote any more time to helping you out. Best of luck.
    cheers,
    Greg

  • Focus on null Jlist Item : Urgent

    I am adding a empty item in JLIST on the click of button & bringing the focus on the the empty item.Now what is happening is it only showing a thin blue line instead of selecting the item properly.

    If I undertand correctly, you are adding null to your ListModel? The DefaultListCellRenderer is a JLabel and
    adjusts its height to the text and font it needs to render in each cell: a null value means no text, which
    leads to a very short cell! From the model side, you may want to rethink adding nulls to your model,
    but if that is indeed what is needed, check out this JList methods: setFixedCellHeight, setPrototypeCellValue

  • Highlighting JList Items

    Hello
    Could anybody let me how to change the color of Few Items of JList. I know how to change the foreground color of an item which is selected. But, I need to show few items of JList in different color.
    Thanks in advance

    please can you tell us where is/are ..., could you able to demostrate your issue, now
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class JListDisabledItemDemo implements ItemListener, Runnable {
        private static final String ITEMS[] = {
            "Black", "Blue", "Green", "Orange", "Purple", "Red", "White", "Yellow"};
        private JList jList;
        private JCheckBox[] checkBoxes;
        private boolean[] enabledFlags;
        @Override
        public void run() {
            JPanel pnlEnablers = new JPanel(new GridLayout(0, 1));
            pnlEnablers.setBorder(BorderFactory.createTitledBorder("Enabled Items"));
            checkBoxes = new JCheckBox[ITEMS.length];
            enabledFlags = new boolean[ITEMS.length];
            for (int i = 0; i < ITEMS.length; i++) {
                checkBoxes[i] = new JCheckBox(ITEMS);
    checkBoxes[i].setSelected(true);
    checkBoxes[i].addItemListener(this);
    enabledFlags[i] = true;
    pnlEnablers.add(checkBoxes[i]);
    jList = new JList(ITEMS);
    jList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jList.setSelectionModel(new DisabledItemSelectionModel());
    jList.setCellRenderer(new DisabledItemListCellRenderer());
    jList.addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
    if (!e.getValueIsAdjusting()) {
    System.out.println("selection");
    JScrollPane scroll = new JScrollPane(jList);
    scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    JFrame f = new JFrame("JList and Colors");
    Container contentPane = f.getContentPane();
    contentPane.setLayout(new GridLayout(1, 2));
    contentPane.add(pnlEnablers);
    contentPane.add(scroll);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(240, 280);
    f.setLocationRelativeTo(null);
    UIManager.put("List.background", Color.red);
    UIManager.put("List.selectionBackground", Color.orange);
    UIManager.put("List.selectionForeground", Color.blue);
    UIManager.put("Label.disabledForeground", Color.magenta);
    SwingUtilities.updateComponentTreeUI(f);
    f.setVisible(true);
    @Override
    public void itemStateChanged(ItemEvent event) {
    JCheckBox checkBox = (JCheckBox) event.getSource();
    int index = -1;
    for (int i = 0; i < ITEMS.length; i++) {
    if (ITEMS[i].equals(checkBox.getText())) {
    index = i;
    break;
    if (index != -1) {
    enabledFlags[index] = checkBox.isSelected();
    jList.repaint();
    public static void main(String args[]) {
    SwingUtilities.invokeLater(new JListDisabledItemDemo());
    private class DisabledItemListCellRenderer extends DefaultListCellRenderer {
    private static final long serialVersionUID = 1L;
    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    if (enabledFlags[index]) {
    return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    Component comp = super.getListCellRendererComponent(list, value, index, false, false);
    comp.setEnabled(false);
    return comp;
    private class DisabledItemSelectionModel extends DefaultListSelectionModel {
    private static final long serialVersionUID = 1L;
    @Override
    public void setSelectionInterval(int index0, int index1) {
    if (enabledFlags[index0]) {
    super.setSelectionInterval(index0, index0);
    } else {
    if (getAnchorSelectionIndex() < index0) {
    for (int i = index0; i < enabledFlags.length; i++) {
    if (enabledFlags[i]) {
    super.setSelectionInterval(i, i);
    return;
    } else {
    for (int i = index0; i >= 0; i--) {
    if (enabledFlags[i]) {
    super.setSelectionInterval(i, i);
    return;

  • Highlight a word within a JList Item

    I would like to highlight a word red within a JList item. For example, a user has a number of words to select from such as can or will. I would like them to select that word and any entries within the list I would like highlighted. I ONLY want the word within a JList item though and not the whole JList item. I know how to do this with a TextField but am having trouble doing this within a JList. Any help would be greatly appreciated.

    Use html syntax to set color/size of a list item. Try this simple example:
    import java.awt.*;
    import javax.swing.*;
    class Testing extends JFrame {
      public Testing() {
        String [] list = {
           "<html><body>Black <font size=15>Black</font> Black",
           "<html><body>Red <font color=red size=10>Red</font> Red ",
           "<html><body>Blue <font color=blue size=5>Blue</font> Blue"
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new BorderLayout());
        JList jlist = new JList(list);
        JScrollPane spane = new JScrollPane(jlist);
        panel.add(spane);
        getContentPane().add(panel);
        setSize(200,200);
      public static void main(String[] args){
        new Testing().setVisible(true);
    }

Maybe you are looking for

  • Metadata issue in PPro - UserClipName populates in Metadata and won't go away

    I have P2 footage that is behaving oddly in PP - PPro CS6.  I am on a PC, using Windows 7 Professional. Footage was shot and archived onto our PC last summer - as is our typical process - and a PP project was started. It was left dormant till now - 6

  • HT4859 where are my pictures in icloud back up?

    I backed up my ipad yesterday to icloud. today I got a message to install update for itunes.  I installed, ipad froze.  I had to restore ipad on itunes.  now I cannot locate my pictures and videos on my icloud.

  • Cursor styles in OS 10.10

    Installed 10.10 and the cursor now takes different shapes for different functions. Sometimes a double arrow in vertical position sometimes same in horizontal authorities at an angles sometimes a line with U (s) on top and bottom and a line thru middl

  • Black 1px Lines in Rendered .FLV

    I don't see any reference to this (yet) in this forum but I hope It doesn't matter if I use AME or render out an .flv from After Effects, I still get a black 1px line top and bottom: http://www.24hourhotline.net/motion.html The video file itself is 6

  • Monitor Color Profile Coming In With Windows Update

    I recently had to revisit the color-management logic in my software, owing to a monitor profile showing up and being installed on users' machines through Windows Update.  Specifically, for some reason a VMware virtual machine running 32 bit Windows 7