Solved

Right Click and Select an item in Jlist

Posted on 2008-09-29
5
1,925 Views
Last Modified: 2013-11-23
Hi,
In the attached code, if I 'Ctrl+left click' and select few items and I right click on top of another item, how can I make the right clicked item selected and the older ones de-selected.
Also, if I 'Ctrl+left click' and select few items and I right click on top of any of these selected items, the selection has to be there on these items(I am trying to implement something similar to file/folder selection in windows -- adding popup menu will be the next step I do).
Regards,
Sreejith
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
 
public class MainClass {
  public static void main(String args[]) throws Exception {
         
    MainClass mc = new MainClass();
    Icon fileIcon = UIManager.getIcon("FileView.fileIcon");
	Icon directoryIcon = UIManager.getIcon("FileView.directoryIcon");
         Object elements[][] = { {"first.doc",fileIcon},
                                                          {"second",fileIcon},      
                                                          {"third",fileIcon} ,
                                                          {"nineth",directoryIcon},
                                                          {"eighth",directoryIcon},
                                                          {"fifth",fileIcon}
          
          
          };
          
 
    JFrame frame = new JFrame("Trial");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
    JList jlist = new JList(elements);
    ListCellRenderer renderer = new ComplexCellRenderer1();
    jlist.setCellRenderer(renderer);
    jlist.setLayoutOrientation(JList.HORIZONTAL_WRAP);
    jlist.setVisibleRowCount(-1);
    JScrollPane scrollPane = new JScrollPane(jlist);
    frame.add(scrollPane, BorderLayout.CENTER);
 
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}
 
class ComplexCellRenderer1 implements ListCellRenderer {
  protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
  public Component getListCellRendererComponent(JList list, Object value, int index,
      boolean isSelected, boolean cellHasFocus) {
    Icon icon = null;
    String theText = null;
    JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,
        isSelected, cellHasFocus);
    renderer.setVerticalTextPosition(JLabel.BOTTOM);
    renderer.setHorizontalTextPosition(JLabel.CENTER);
 
 
    if (value instanceof Object[]) {
      Object values[] = (Object[]) value;
      theText = (String) values[0];
      icon = (Icon) values[1];
    } else {
      
    }
    renderer.setText(theText);
    renderer.setIcon(icon);
    return renderer;
  }
}

Open in new window

0
Comment
Question by:Sreejith22
  • 3
  • 2
5 Comments
 
LVL 9

Accepted Solution

by:
arioh earned 500 total points
ID: 22603183
   jlist.addMouseListener( new MouseAdapter(){
      public void mouseClicked( MouseEvent Evt ) {
        if ( Evt.getButton() == MouseEvent.BUTTON3 ) {
          int Idx = jlist.locationToIndex( Evt.getPoint() );
          if ( Idx >= 0 ) {
            Rectangle Rect = jlist.getCellBounds( Idx, Idx );
            Idx = Rect.contains( Evt.getPoint().x, Evt.getPoint().y ) ? Idx : -1;
          }
          if ( Idx < 0 || !jlist.getSelectionModel().isSelectedIndex( Idx ) ) {
            jlist.getSelectionModel().clearSelection();
            if ( Idx >= 0 )
              jlist.getSelectionModel().setSelectionInterval( Idx, Idx );
          }
        }
      }
    } );
0
 

Author Closing Comment

by:Sreejith22
ID: 31501466
Thanks alot. The full points are for you.
0
 

Author Comment

by:Sreejith22
ID: 22603217
Thanks arioh
0
 

Author Comment

by:Sreejith22
ID: 22603325
The mouse event 'Evt' returns false for popupMenu.isPopupTrigger(Evt) . So I am not able to generate popup menu.
Please help
0
 
LVL 9

Expert Comment

by:arioh
ID: 22603434
check for isPopupTrigger() in mouseReleased method

      public void mouseReleased( MouseEvent Evt ) {
        if ( Evt.isPopupTrigger() ) {
          System.out.println( "popup" );
        }
      }

from the JDK API:
Note: Popup menus are triggered differently on different systems. Therefore, isPopupTrigger should be checked in both mousePressed and mouseReleased for proper cross-platform functionality.
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
ForLoop Example 3 49
diffSum example 4 37
SHA2 certs for IIS AND Java? 2 91
Java exception bubble up 2 18
Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question