Solved

Right Click and Select an item in Jlist

Posted on 2008-09-29
5
1,921 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Programmer's Notepad is, one of the best free text editing tools available, simply because the developers appear to have second-guessed every weird problem or issue a programmer is likely to run into. One of these problems is selecting and deleti…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

867 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now