Overriding Default JTable Selection Behavior

I'm attempting to override the default selection behavior of a JTable. For clicking, I want the table to behave basically as if the ctrl key was being held down all the time. That works great.
I want the behavior of dragging a selection to behave a certain way as well. If ctrl is not held down, then a drag should cancel the current selection and start a new one at the drag interval. This works fine too.
However, if ctrl is held down during a drag, I want the dragged interval to be added to the selection instead of replacing it. This almost works. However, if I hold ctrl while dragging, it no longer let's me "undrag" the selection: once a cell is inside the dragged interval, it's selected, even if you drag back over it to deselect it.
I understand why that's happening given my approach, but I'm looking for a way around it. Does anybody have any ideas about how to get a JTable to behave the way I want?
Here's a compilable program that demonstrates what I'm doing:
import javax.swing.*;
import java.awt.event.*;
public class TestTableSelection{
     boolean ctrlDown = false;
     JTable table;
     public TestTableSelection(){
          JFrame frame = new JFrame("Test Table Selection");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          //give the table random data
          String [][] data = new String [10][5];
          String [] names = new String [5];
          for(int i = 0; i < 5; i++){
               names[i] = "C: " + i;
               for(int j = 0; j < 10; j++){
                    data[j] = "t: " + (int)(Math.random()*100);
          table = new JTable(data, names){
               //override the default selection behavior
               public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
                    if(ctrlDown){
                         //ctrl + dragging should add the dragged interval to the selection
                         super.changeSelection(rowIndex, columnIndex, toggle, extend);     
                    else{
                         //clicking adds a row to the selection without clearing others
                         //dragging without holding ctrl clears the selection
                         //and starts a new selection at the dragged interval
                         super.changeSelection(rowIndex, columnIndex, !extend, extend);
          //keep track of when ctrl is held down
          table.addKeyListener(new KeyAdapter() {
               public void keyPressed(KeyEvent e) {
                    ctrlDown = e.isControlDown();
               public void keyReleased(KeyEvent e){
                    ctrlDown = e.isControlDown();
          frame.getContentPane().add(new JScrollPane(table));
          frame.setSize(250, 250);
          frame.setVisible(true);
     public static void main(String[] args){
          new TestTableSelection();
Let me know if any of that isn't clear.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

This change seemed to work for me
          table = new JTable(data, names){
               int prevRow = -1;
               //override the default selection behavior
               public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
                    if(ctrlDown){
                         //ctrl + dragging should add the dragged interval to the selection
                         if ( rowIndex != prevRow ) {
                              prevRow = rowIndex;
                              super.changeSelection(rowIndex, columnIndex, true, false);
                    else{
                         //clicking adds a row to the selection without clearing others
                         //dragging without holding ctrl clears the selection
                         //and starts a new selection at the dragged interval
                         super.changeSelection(rowIndex, columnIndex, !extend, extend);
          };

Similar Messages

  • Limit JTable selection behavior

    I have a simple table with 3 columns an multiple rows. If I select a row with the left mouse button and, with out letting go, move the mouse pointer up to a higher row or down to a lower row the currently selected row changes to the row the mouse pointer is over.
    I need to stop this behavior.
    If I select a row with a left mouse press and move the mouse around when I do a mouse release I want the selected row to still be the one i did the mouse pressed action over.
    Please Help.

    This change seemed to work for me
              table = new JTable(data, names){
                   int prevRow = -1;
                   //override the default selection behavior
                   public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
                        if(ctrlDown){
                             //ctrl + dragging should add the dragged interval to the selection
                             if ( rowIndex != prevRow ) {
                                  prevRow = rowIndex;
                                  super.changeSelection(rowIndex, columnIndex, true, false);
                        else{
                             //clicking adds a row to the selection without clearing others
                             //dragging without holding ctrl clears the selection
                             //and starts a new selection at the dragged interval
                             super.changeSelection(rowIndex, columnIndex, !extend, extend);
              };

  • Overriding default Cntl Shift Drag Behavior

    Control Shift Drag cancels out the whole drag operation if i m not wrong.. How can i disable this..

    This change seemed to work for me
              table = new JTable(data, names){
                   int prevRow = -1;
                   //override the default selection behavior
                   public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
                        if(ctrlDown){
                             //ctrl + dragging should add the dragged interval to the selection
                             if ( rowIndex != prevRow ) {
                                  prevRow = rowIndex;
                                  super.changeSelection(rowIndex, columnIndex, true, false);
                        else{
                             //clicking adds a row to the selection without clearing others
                             //dragging without holding ctrl clears the selection
                             //and starts a new selection at the dragged interval
                             super.changeSelection(rowIndex, columnIndex, !extend, extend);
              };

  • [JTable] prepareRenderer() override and foreground selection setting

    Hello,
    I can't solve this problem :
    To get a JTable's cell blinking in different colors, I overrided the JTable's prepareRenderer() method : this works fine.
    "But", because there's always a butt, if I restore the cell default background and foreground color when I want the cell to stop blinking, I lose the cell selection foreground color. If I don't restore those colors, the cell selection foreground color (translucent blue) is kept, but cell background and foreground colors will remain in the last blinking state.
    Can you see why or should I submit it as a Java bug (I already read and followed other topics on cell blinking, but it doesn't cover this very point) ?
    Here is the problematic code snippet (to get this method called, I manually and regularly trigger a fireTableCellUpdated() in a thread). The alternative issue is commented in it :
            public Component prepareRenderer(TableCellRenderer renderer,int row,int column) {
                Component res;
                res = null;
                res = super.prepareRenderer(renderer,row,column);
                // conditions required to make the cell blink
                if(
                   (isRunningThreadNewLog) &&
                    (row == 0) &&
                    (column == 0)
                   (! isCellSelected(row,column))
                    res.setBackground(newItemColor[0][lastItemColorIndex]);
                    res.setForeground(newItemColor[1][lastItemColorIndex]);
                    lastItemColorIndex = (lastItemColorIndex + 1) % newItemColor[0].length;
                * Here is where the problem occurs :
                *  - if I build ans runs as it, cell selection foreground will be painted with the default translucent blue color, but cell background and foreground colors won't be reset
                *  - if I uncomment, build and run, ccell background and foreground colors will be paint, but cell forground will be lost, or exactly, it will be painted to the cell foreground color, not the cell selection foreground color
               else {
                    res.setBackground(defaultItemColor[0]);
                    res.setForeground(defaultItemColor[1]);               
                return res;
            }Thanks for help :)
    Edited by: Rockz on Mar 5, 2009 1:19 PM

    or should I submit it as a Java bugLets see, you write some custom code and it doesn't work the way you want it to, so it must be a Java bug?
    Did you ever think it might be a problem with your code?
    First of all, whats with all the brackets in the if statement? Why do you try to group the row and column test?
    So lets take a look at your code. You have 4 conditions. If any one of them fail then you will go into the "else" which automatically resets the foreground and background colors "even" if the isCellSelected() test is true.
    Basically, the isCellSelected should be a separate test. Maybe something like:
    if (! isCellSelected(...))
        if (isRunningThreadNewLog
        && row == 0
        && column == 0)
            // do something
        else
            // do something else
    }If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • JTable selection visible

    Is it possible to set a table or list selection always visible ?
    And if yes, How ? (of course)
    Thanks

    Not sure if this will help you but I had a similar issue when sorting a table. After the sort a tableChanged event is issued and the default JTable behavior is to clear the selection. As part of the tableChanged event processing I attempted to reset a selection by calling setRowSelectionInterval() but the selection never showed up.
    What eventually worked was to schedule the row selection on the event thread via SwingUtilities.invokerLater() instead of issuing the call from the tableChanged method.

  • [Forum FAQ] How to disable Microsoft account default sign-in behavior when accessing Microsoft website on Windows 8.1

    Scenario
    By default it will sign in with current Microsoft account, if a user accesses Microsoft website (www.live.com, www.bing.com, etc.) with Microsoft account on Windows 8.1. This article describes how to disable this default sigh-in behavior if you want to use
    different Microsoft accounts every time. 
    Method
    To disable this default sign-in behavior, we can deny current Microsoft Account read permission of MicrosoftAccountTokenProvider.dll, please follow the following steps:
    Run Command Prompt with elevated permissions.
    Run the following command to take ownership of MicrosoftAccountTokenProvider.dll:
      takeown /f C:\Windows\SysWOW64\MicrosoftAccountTokenProvider.dll
    Run the following command to deny the read permission of the Microsoft:                                
     icacls C:\Windows\SysWOW64\MicrosoftAccountTokenProvider.dll /deny
    [email protected]:r                                                                                                                
    Note: Please replace your current Microsoft Account with the example
    [email protected]
    Change the owner of this file back to TrustedInstaller:
    Right-click MicrosoftAccountTokenProvider.dll under
    C:\Windows\SysWOW64\, choose Properties. Under
    Security tab, click Advanced.
    Click Change, in the box Enter the object name to select, type
    NT Service\TrustedInstaller.
    Click OK.
    Note: This operation would take some hours to work.
    Apply to:
    Windows 8.1
    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

    Error: System cannot find the specified path
    I am getting this eroor
    Parashuram Singade www.distinctnotion.com

  • JDK1.5 table selection behavior has changed

    The default extended selection policy of JTables has changed from version 1.4.2 to 1.5.
    In 1.4.2, a user can hold down the Ctrl key and drag out a multi-row selection. The user can then hold down the Ctrl key again and drag out a second multi-row selection which leaves the first multi-row selection intact. The end result was 2 discontiguous multi-row selections.
    Now in 1.5, the process of making the second multi-row selection clears out the first. Basically any Ctrl+Drag gesture is clearing out any existing selections. This is dangerous since a user that wants to Ctrl+Click several discontiguous rows may slightly move the mouse on each click. This will be interpreted as a Ctrl+Drag and cause all existing selection to be cleared.

    I don't remember being able to do that in 1.4.2_04 without some special code. Well, at least not for a JList, never tried on a JTable. Anyway, you should make a bug for it if it's not alreay there.

  • Modifying JList selection behavior

    What I want to do is change the selection behavior so that if the user clicks on the left half of the cell, the item is selected, but if the user clicks on the right half, the item is not selected. I already have the code to determine where the user clicked, but can't get the selection to not occur when I determine that the user clicked in the "non-selection area" right half.

    After overriding...
    public void setSelectedIndices(int[] indices)
    public void setSelectedValue(Object anObject, boolean shouldScroll)
    public void setSelectionInterval(int anchor, int lead)
    public void setSelectedIndex(int index)...it worked. I implemented each of these like this.
    public void methodX()
      if( clickOnSelectableRegion )
        super.methodX();
      clickOnSelectableRegion = true;
    }It is the responsibility of an outside MouseListener to determine if the click falls on a selectable region or not. If a click occurs that is not on a selectable region, the listener should call setOnSelectableRegion(false) on the List. I set the value back to true so the listener only has to notify the list of "ignorable" clicks.

  • Override Default Page Activation Workflow

    Hello,
    I am trying to override the default handling of Authors requesting page activations.  By default, an Author that doesn’t have Replication privileges has the request sent to the Admin group.  We’ve created several workflows specifically for different groups since each has their own approval flow:
    CQ User Group                 CQ Workflow
    Consumer >>                     Consumer Approval Workflow
    eCRM >>                             Consumer Approval Workflow
    Business >>                        Business Approval Workflow
    I realize the Author could select the workflow from the Sidekick, but I need ot ensure the correct workflow is assigned if they simply click “Activate” from the Sidekick or the Site Admin (Websites) page.  What’s the best way to accomplish this – writing some sort of servlet, using the Dynamic Participant Step, something else?  The logic would be fairly straight forward – on activation request, check user group and assign page to pre-defined workflow and initiate.

    You can set this in version 5.1.
    Thanks,
    Michael
    Michael Girdley
    BEA Systems Inc
    "anil" <[email protected]> wrote in message
    news:399aba85$[email protected]..
    How we can override default error page (404) in WebLogic ver 4.5.1 ? Wehave already set property weblogic.httpd.errorPage.404=URL in
    weblogic.properties file , but it is not working with 4.5.1
    >
    We would like to have solution in properties setting, because changing thecode is not possible
    >
    Thanks in Advance
    anil

  • "resolving alias to" message using aliases on 10.6.8 plus slow text-selection behavior

    Recently after no particular change to my Mac Pro3,2 running 10.6.8 other than some routine software updates, whenever I open an alias on my desktop to standard folders or files, a message shows up "Resolving alias to" whatever the alias name and there's a 2-3 second delay before the folder/file opens. I've found discussion of this issue in some archived discussions but never found a comfirmed solution described, so I'm raising this again. As in others' encounter with this behavior, the slow opening of aliases happens (1) only in my own user account, not in a guest account I set up for test purposes [I have no other user accounts than these], and (2) only happens the FIRST time I open an alias. Subsequent uses of the alias work normally.
    Another strange but possibly related behavior that began at the same time as this alias delay is harder to describe but involves a problem when selecting text using mouse clicks or even highlighting with the mouse for editing. For example, to edit the name of a file or folder on my desktop, I would normally click on the file/folder name, pause a moment and click again: this puts me in edit mode with the current file/folder name highlighted/selected. Now when I attempt this procedure, the second time I click immediately opens the file/folder, as though I had double-clicked rather than clicked+paused+clicked. The only way I can select the name of the file/folder to edit it is to click+long pause (like 3 seconds)+click. Then the text is selected as desired. It's as though the clicks are being recognized (by whatever in the OS recognizes clicks) as much faster than actually made.  There is a similar problem in any program I use that permits text editing, whether Word (Office 2011 for Mac), TextEdit, etc. I have to consciously slow down my cursor/click behavior when selecting text. If not, my actions are misinterpreted as double clicks. This text selection behavior also disappears when using a "Guest" user account, only appearing in my own user account. I Using a different mouse has no effect.
    Steps taken so far. I've Repaired Disk Permissions and Verified Disk using Disk Utility, have Safe Booted, and have turned off all login items in my user account,and recently installed the 10.6.8 supplemental update, all to no avail. Any suggestions or has anyone had and solved this/these problems?

    I think my problem has been that in Sytem Preferences>Mouse, my "Double-Click Speed" was set to the SLOWEST setting. After some experimentation, I now have the that setting two notches from the "Fast" end of the scale. In case it's important, the "Primary mouse button" in my Preferences is set to "Left".
    This not only solves the text selection issues described, but also seems to eliminate the strange "resolving alias to" problem.
    [For the curious, I have a Logitech Performance MX wireless mouse which can be configured with "Logitech Control Center". But the LCC software doesn't control double-click speed; this setting can only be made in the Mouse System Preference pane.]

  • How do you turn off the auto select behavior when working with shape layers?

    How do you turn off the auto select behavior when working with shape layers?
    I am using either of the path selection tools to select only some of the paths on the layer. I have the proper layer targeted. I have the selection too auto select option turned off.
    If another layer has a path in that area, that layer becomes auto targeted and I get the wrong path. Turning off the layer is the only way to avoid this but then I have to  turn on the layer back on between making my selection and transforming to use the other layer as guide. Is there any way to stop this auto select? Locking the other layer does not stop the auto select, just prevents editing.

    As far as i know the move tool options don't have any effect on the path selection tools.
    You might try clicking on one of the path points or on the path itself with one of path selection tools and if you want to select multiple points
    you can shift click with the Direct Selection Tool or Alt click to select the entire path.
    more path shortcuts:
    http://help.adobe.com/en_US/photoshop/cs/using/WSDA7A5830-33A2-4fde-AD86-AD9873DF9FB7a.htm l
    http://help.adobe.com/en_US/photoshop/cs/using/WSfd1234e1c4b69f30ea53e41001031ab64-7391a.h tml

  • How do I change the default '/' shortcut (select none in colour swatch) to something different? Where can i find it in Keyboard Shortcuts?

    How do I change the default '/' shortcut (select 'none' in colour swatch) to something different? Where can i find it in Keyboard Shortcuts?
    Any ideas?

    Thanks so much )))))))

  • Need help with Default Parameter selection

    Hi there ,
    I'm using SSRS 2012 and I've 2 level cascading parameter (section depends on division parameter).
    Division 10 has 2 sections which are 10 and 11.
    Division 20 has 2 section which are 20 and 21.
    Division 30 has 1 section which is 31.
    Division 60 has 2 sections which are 60 and 61.
    I want to set default values to min - max values of Section parameter depends on current values of division parameter.
    In the picture below is the correct result.
    Problem will occur when changing Division.To from 20 to 60.
    I expect the Section.To must changed to max value of it(61) instead the current value(21) like picture below.
    I've checked the query operation using SQL Profiler that tell me the Min - Max dataset of Section parameter NOT BEING FIRED when I change
    Division.To selection.
    FYI.
    I'm using 2 datasets separate for available,default values in each parameter.
    i.e. Section.To parameter  
    1. available values
    SELECT DISTINCT(SectionCode)
    FROM Section
    WHERE DivisionCode BETWEEN @DivFrom and @DivTo
    2. default values
    SELECT MAX(SectionCode) Max
    FROM Section
    WHERE DivisionCode BETWEEN @DivFrom and @DivTo
    Can you give me some advice how to fix this problem ?
    Thank you in advance.
    SweNz

    Hi,
    I had used one sample table to populate your data on top of it i had created report with parameters and got the result as u expected (Hope). Check the below contents to simulate the requirement.
    =====================================================
    CREATE TABLE div_sec
    division int,
    section int,
    range int
    INSERT INTO div_sec (division,section,[range]) values ()
    INSERT INTO div_sec (division,section,[range]) values (10,10,0)
    INSERT INTO div_sec (division,section,[range]) values (10,11,1)
    INSERT INTO div_sec (division,section,[range]) values (20,20,0)
    INSERT INTO div_sec (division,section,[range]) values (20,21,1)
    INSERT INTO div_sec (division,section,[range]) values (30,31,0)
    INSERT INTO div_sec (division,section,[range]) values (30,31,1)
    INSERT INTO div_sec (division,section,[range]) values (60,60,0)
    INSERT INTO div_sec (division,section,[range]) values (60,61,1)
    SELECT * FROM div_sec
    --Created 3 Datasets with the below queries
    --ds_Div
    SELECT distinct division FROM div_sec
    --ds_Sec_Min
    SELECT division, section
    FROM div_sec
    WHERE (range = 0) AND division = @div
    --here for @div assign the value from @DivFrom Parameter
    --ds_Sec_Max
    SELECT division, section
    FROM div_sec
    WHERE (range = 1) AND division = @div
    --here for @div assign the value from @DivTo Parameter
    --Create the 4 parameters
    --DivFrom
    --in available value select the ds_Div dataset
    --DivTo
    --in available value select the ds_Div dataset
    --SecFrom
    --in available and default value select the ds_Sec_Min dataset
    --SecTo
    --in available and default value select the ds_Sec_Max dataset
    =====================================================
    Sridhar

  • In the Date Picker, How can I default to select * dates if the user does ..

    In the Date Picker, How can I default to select * dates if the user does not select a date.
    Thanks,
    Doug

    Doug,
    Now lets say l want everythingCould you post some sample data and the output that you want to get..? It would be much easy to understand the requirements...
    When you mean everything, I am assuming you need all possible dates possible between date1 and date2.
    you can use... (from asktom.oracle.com).
      1  select to_date('12-jan-2009','DD-MON-YYYY') + rownum -1
      2    from ALL_OBJECTS
      3    where rownum <= (to_date('20-jan-2009','dd-mon-yyyy') -
      4*                     to_date('12-jan-2009','DD-MON-YYYY') +1 )
    sql> /
    TO_DATE('
    12-JAN-09
    13-JAN-09
    14-JAN-09
    15-JAN-09
    16-JAN-09
    17-JAN-09
    18-JAN-09
    19-JAN-09
    20-JAN-09
    9 rows selected.
    For your case, since you have date1 and date2...
    select to_date(:p12_date1,'DD-MON-YYYY') + rownum -1
      from ALL_OBJECTS
      where rownum <= (to_date(:p12_date2,'dd-mon-yyyy') -
                        to_date(:p12_date1,'DD-MON-YYYY') +1 )Should work.. in my opinion...Haven't tested the second one in Apex .
    Is this what you were looking for ..?? If not, please elaborate...
    Thanks,
    Rajesh.

  • Problem overriding default JSF conversion error messages

    Hello !
    I have a problem to override default JSF conversation error message. I have an inputText which is binded to BigDecimal attribute, so when I enter a character in that field I get this error message: "- Conversion failed."
    I think I need to register the message bundle in my faces config, and put the key of this error message to my properties file.. am I right ?
    Can somebody help me with this ? Which key I need to put into the properties file ?
    Miljan

    Get [Sun's Java EE tutorial |https://www.sun.com/offers/details/JavaEETutorial.xml?cid=20090723ZA_TACO_JVEE_0004] and read the relevant section so you don't have to guess what you need to do.

Maybe you are looking for

  • Spilled beer on my X300 | Mein teil

    This is also my story with X300. I have 4 notebooks at the moment, two are Toshiba other two are Thinkpads. I dreamed about X300, it just amazed me, and after I got it, paid loads of cash for it (I paid in cash) ~2400 euros, after I rejected the fact

  • Changing an NSView in Xcode 3

    Hey there, I'm pretty new to progamming for the mac and I'm having a pretty hard time with Xcode 3. It seems that most of the tutorials and example code out there is aimed at earlier versions of Xcode and there aren't many books for it as well. I com

  • Captivate 8 modules exported in SCORM 1.2

    hello there, I need help with Captivate 8 modules exported in SCORM 1.2 Placed on an LMS, the modules do not work. below the results on cloud.scorm.com.

  • Lr 5 appears two times in my creative cloud apps tool

    Hello, when I opened the creative cloud tool for updating to CC 2014 and Lr 5.5, I recognized that Lr 5 was mentioned two times. For the 'first Lr', there was a button update which I used to update for 5.5, and next to the second, there was no update

  • ICON for a Button( Forms 4.5)

    I am trying to show an ICON for a Button in Forms 4.5 under Windows OS. I am not able to find any of these TK_ICON, UI_ICON and TK25_ICON in the registry to set the path. Shoud I have to install any other utility/option ? please guide me