JTable SelectionModel - first Index and Las Index giving incorrect values

Hi Guys,
When i added a ListSelectionListener to the JTable's selectionModel, and tried to get the first index and last index values. The goofy thing i noticed is when you select different rows, the indexes are correct,but when you switch between the same rows, then indexes provided by the ListSelectionListener are always the same. Example : if you switch between 3 and 4 rows first index is 2 and last index is 3 which is correct, but if you go back 3rd row from 4th row, the first index is still 2 and last index is 3... which is kind of weird.
Any ideas about this, and why this is happenning.
I am pasting my sample code here any explanation is very helpfull to understand this behavior
Thanks
Nicedude
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JComponent;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
* SimpleTableSelectionDemo is just like SimpleTableDemo,
* except that it detects selections, printing information
* about the current selection to standard output.
public class SimpleTableSelectionDemo extends JPanel {
     private boolean DEBUG = false;
     private boolean ALLOW_COLUMN_SELECTION = false;
     private boolean ALLOW_ROW_SELECTION = true;
     public SimpleTableSelectionDemo() {
          super(new GridLayout(1,0));
          final String[] columnNames = {"First Name",
                    "Last Name",
                    "Sport",
                    "# of Years",
          "Vegetarian"};
          final Object[][] data = {
                    {"Mary", "Campione",
                         "Snowboarding", new Integer(5), new Boolean(false)},
                         {"Alison", "Huml",
                              "Rowing", new Integer(3), new Boolean(true)},
                              {"Kathy", "Walrath",
                                   "Knitting", new Integer(2), new Boolean(false)},
                                   {"Sharon", "Zakhour",
                                        "Speed reading", new Integer(20), new Boolean(true)},
                                        {"Philip", "Milne",
                                             "Pool", new Integer(10), new Boolean(false)}
          final JTable table = new JTable(data, columnNames);
          table.setPreferredScrollableViewportSize(new Dimension(500, 70));
          table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
          if (ALLOW_ROW_SELECTION) { // true by default
               ListSelectionModel rowSM = table.getSelectionModel();
               rowSM.addListSelectionListener(new ListSelectionListener() {
                    public void valueChanged(ListSelectionEvent e) {
                         //Ignore extra messages.
                         if (e.getValueIsAdjusting()) return;
                         ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                         if (lsm.isSelectionEmpty()) {
                              System.out.println("No rows are selected.");
                         } else {
                              int selectedRow = lsm.getMinSelectionIndex();
                         System.out.println("Row " + selectedRow + " is now selected.");
                              int first = e.getFirstIndex();
                                                        int last = e.getLastIndex();
                          System.out.println(" First Index is : " + first);
                          System.out.println(" Last Index is : " + last );
          } else {
               table.setRowSelectionAllowed(false);
          if (ALLOW_COLUMN_SELECTION) { // false by default
               if (ALLOW_ROW_SELECTION) {
                    //We allow both row and column selection, which
                    //implies that we *really* want to allow individual
                    //cell selection.
                    table.setCellSelectionEnabled(true);
               table.setColumnSelectionAllowed(true);
               ListSelectionModel colSM =
                    table.getColumnModel().getSelectionModel();
               colSM.addListSelectionListener(new ListSelectionListener() {
                    public void valueChanged(ListSelectionEvent e) {
                         //Ignore extra messages.
                         if (e.getValueIsAdjusting()) return;
                         ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                         if (lsm.isSelectionEmpty()) {
                              System.out.println("No columns are selected.");
                         } else {
                              int selectedCol = lsm.getMinSelectionIndex();
                              System.out.println("Column " + selectedCol
                                        + " is now selected.");
          if (DEBUG) {
               table.addMouseListener(new MouseAdapter() {
                    public void mouseClicked(MouseEvent e) {
                         printDebugData(table);
          //Create the scroll pane and add the table to it.
          JScrollPane scrollPane = new JScrollPane(table);
          //Add the scroll pane to this panel.
          add(scrollPane);
     private void printDebugData(JTable table) {
          int numRows = table.getRowCount();
          int numCols = table.getColumnCount();
          javax.swing.table.TableModel model = table.getModel();
          System.out.println("Value of data: ");
          for (int i=0; i < numRows; i++) {
               System.out.print("    row " + i + ":");
               for (int j=0; j < numCols; j++) {
                    System.out.print("  " + model.getValueAt(i, j));
               System.out.println();
          System.out.println("--------------------------");
      * Create the GUI and show it.  For thread safety,
      * this method should be invoked from the
      * event-dispatching thread.
     private static void createAndShowGUI() {
          //Make sure we have nice window decorations.
          JFrame.setDefaultLookAndFeelDecorated(true);
          //Create and set up the window.
          JFrame frame = new JFrame("SimpleTableSelectionDemo");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          //Create and set up the content pane.
          SimpleTableSelectionDemo newContentPane = new SimpleTableSelectionDemo();
          newContentPane.setOpaque(true); //content panes must be opaque
          frame.setContentPane(newContentPane);
          //Display the window.
          frame.pack();
          frame.setVisible(true);
     public static void main(String[] args) {
          //Schedule a job for the event-dispatching thread:
          //creating and showing this application's GUI.
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    createAndShowGUI();
}

>
I was (maybe wrongly) under the impression that, last index will give the last selected value and first index will give me the currect selected value. Not maybe - your impression sure is wrong. Honestly can't understand how it's possible to mis-interpret the api doc of ListSelectionEvent (except not reading it ;-)
"Represents a change in selection status between firstIndex and
lastIndex, inclusive. firstIndex is less than or equal to
lastIndex. The selection of at least one index within the range will
have changed."
Jeanette

Similar Messages

  • CDS-18010 Error:A Index and a index with the same name

    Hi
    I am facing strange error is some one expert there to help me to get rid of this error.
    CDS-18010 Error:A Index and a index with the same name 'LA_SP_FK_1' have been asked to be created.
    I am generating tables from Data model diagram & getting this error.
    Thanks,
    Vijay

    Your Right!!
    Designer does not like 2 of the same name.
    there are several bugs on the same name issue and CDS-18010
    Bug.3973155/3443005 (92) CDS-18010 IN CAPTURING A TYPE WITH CONSTRUCTOR FUNTIONS IN ITS BODY:
    Bug.2586582 (93) CDS-18010 A DOMAIN AND A DOMAIN WITH THE SAME NAME 'D1' BEEN ASKED TO CREATE:
    Bug.2561625 (15) CDS-18010 GENERATION OF TWO SYNONYMS WITH SAME NAME BUT DIFFERENT SCOPE:
    Bug.2072505 (93) CDS-18010 CAPTURING 2 TRIGGERS WITH SAME NAME ON ONE TABLE SHOULD BE A WARNING:
    Bug.1689800 (90) CDS-18010 PLSQL WITH THE SAME PROCEDURE NAME ALREADY EXISTS:
    Bug.1073311/1029997 (96) CDS-18010 ERROR ATTEMPTING TO CREATE 2 PROCEDURES WITH SAME NAME:
    Just to name a few.
    I would suggest you change the name.
    Michael

  • How get column index and row index in gridpane of javafx

    how get column index and row index in gridpane of javafx. see the code below
    Text text1 = new Text("Text 1");
    Text text2 = new Text("Text 2");
    StackPane root = new StackPane();
    GridPane gridPane = new GridPane();
    gridPane.add(text1, 0, 0);
    gridPane.add(text2, 1, 0);
    When Mouse Entered On text1 i want to get the column index and row index of GridPane
    text1.setOnMouseEntered(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent e) {
                    //want to get column index =0 and row index=0
    Please let me know.

    Hi,
    If I remember well:
    [code]
    text1.setOnMouseEntered(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent e) {
                    //want to get column index =0 and row index=0
                    System.out.println("Column: " + GridPane.getColumnIndex(text1));
    [/code]
    -- daniel

  • Differences between function based index and normal index

    Hi,
    Please Give me some differences between function based index and normal indexes.
    1. Is there any performance gain in function based index?
    2. Why indexes created in DESC are treated as function based?
    3. Every DESC index is b-tree index?
    Thanks

    check this link. This would give u a basic idea of what a function based index is .
    http://www.oracle-base.com/articles/8i/FunctionBasedIndexes.php
    --Prasad                                                                                                                                                                                                                                                                                                                                       

  • Difference bet cube indexes and dso indexes

    hi,
    1.can any tell me the difference between cube indexes and dso indexes?
    if we have aggregates on the cube it improves the performce of the query created on it
    2.so why to create indexes on the cube?
    for creating indexes on the dso i right click on dso and click create indexes
    it is asking two options
    1.unique key 2.non unique
    4.what is the functionality of these two?
    i will assign points if ur answers clear my questions

    The BW automatically defines multiple indexes on your cubes, based on the dimensions you have defined.  You do not need to create any additional indexes on your Fact tables.  It can somtimes be helpful to create a secondary index on dimension tables or master data tables depending on their size and the queries.  There is not BW wkbench tool to do this, it usually requires a DBA in most shops.
    Secondary indexes on DSO/ODS can help some queries substantially, again, depending on the data and the queries.  You can define secondary indexes on DSO/ODS from the BW workbench.
    Aggregates are another tool for query performance, by summarizing the data, it can reduce the number of rows that must be read by a query.  Again, it dpends on the query and the data as to how much an aggregate helps.

  • Multitouch.maxTouchPoints giving incorrect values for Google Nexus S

    Just testing out the Adobe multitouch example application (http://www.adobe.com/devnet/flash/articles/multitouch_gestures.htm_phases-16569.html) and have discovered that Multitouch.maxTouchPoints is giving incorrect values (2) for my Google Nexus S (5+).
    If any devs are listening, can you give me more information? Should I report a bug?

    The runtime team is aware of this issue.  I believe it may return 2 for many if not all devices.

  • What is the difference between the drop and create the index and rebuild index ?

    Hi All,
    what is the difference between drop and create index & rebuild index ? i think both are same...Please clarify if both are same or any difference...
    Thanks in Advance,
    rup

    Both are same. Rebuilding an index drops and re-creates the index. 
    Ref:
    SSMS - https://technet.microsoft.com/en-us/library/ms187874(v=sql.105).aspx
    TSQL - https://msdn.microsoft.com/en-us/library/ms188388.aspx
    I would suggest you to also refer one of the best index maintenance script as below:
    https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html

  • Data deletion on primary index and secondary index

    Hello, I have a question regarding data deletion in BDB-JE.
    Suppose I have an Entity class which has a primary index and a secondary index, the secondary key does not have outer related entity. So when I want to delete this entity, is it correct we only need to remove the entity from primary index? or I also need to do it for secondary index or just remove it from secondary index and internally BDB_JE will remove it from primary index?
    Thanks
    Anfernee

    You can delete an Entity using the delete method for primary index or the secondary index. When an entity is deleted, secondary index records are automatically deleted. The primary and secondary indices are always kept in sync.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Prefix Index and Substing Index not working

    Dear all,
    I'm trying to set the following preference to create my index:
    begin
    ctx_ddl.create_preference('substring_pref', 'BASIC_WORDLIST');
    ctx_ddl.set_attribute('substring_pref','PREFIX_INDEX','TRUE');
    ctx_ddl.set_attribute('substring_pref','PREFIX_MIN_LENGTH',3);
    ctx_ddl.set_attribute('substring_pref','PREFIX_MAX_LENGTH',15);
    ctx_ddl.set_attribute('substring_pref','SUBSTRING_INDEX','TRUE');
    end;
    create index artikel_test_idx
    on artikel_test (art_content)
    indextype is ctxsys.context
    parameters ( 'WORDLIST substring_pref' )
    The index is created sucessfully.
    Here is the data I have in my table:
    ART_INHOUD ART_TITEL ART_CONTENT
    1 Titel1 prion alzheimer
    2 Titel2 prion word1 alzheimer
    3 Titel3 prion word2 word3 alzheimer
    4 Titel4 prion
    5 Titel5 alzheimer
    6 Titel6 alzheimer prion
    7 Titel7 alzheimer word1 prion
    8 Titel8 something else
    9 Titel9 prion alzheimer prion alzheimer
    10 Title10 i am theree
    11 Title11 contract initiation work
    12 Title12 oracle university else
    12 rows selected.
    I test the substring feature by searching for "alz". It should returns me all lines that contains "alzheimer". Am I right? But the result show nothing:
    select art_titel, score(1) as score
    from artikel_test
    where contains (art_content, 'alz', 1) > 0
    no rows selected
    If I search for the entire word, it works:
    select art_titel, score(1) as score
    from artikel_test
    where contains (art_content, 'alzheimer', 1) > 0;
    ART_TITEL SCORE
    Titel9 7
    Titel7 4
    Titel6 4
    Titel5 4
    Titel3 4
    Titel2 4
    Titel1 4
    7 rows selected.
    I look at the table DR$ARTIKEL_TEST_IDX$I and all works are in it:
    TOKEN_TEXT
    ALZ
    ALZH
    ALZHE
    ALZHEI
    ALZHEIM
    ALZHEIME
    ALZHEIMER
    ALZHEIMER
    AM
    CON
    CONT
    CONTR
    CONTRA
    CONTRAC
    CONTRACT
    CONTRACT
    Why there is no result when I search for 'alz'?
    Regards,
    Yanick
    Message was edited by:
    yankee75

    The prefix_index and substring_index do not make the substrings searchable as individual words. They just speed up wildcard queries. If you search for "alt" you will only get rows that have the word "alt" in it. If you search for "alt%" you will get all rows that contain words that begin with "alt". Here are some quotes from the Oracle Text Reference, which is part of the Oracle online documentation:
    "substring_index      Specify TRUE for Oracle Text to create a substring index. A substring index improves left-truncated and double-truncated wildcard queries such as %ing or %benz%. Default is FALSE."
    "prefix_index      Specify TRUE to enable prefix indexing. Prefix indexing improves performance for right truncated wildcard searches such as TO%. Defaults to FALSE."

  • Error in Process chain while deleting index and create index

    While executing the process chain  for delete index  the process chain failed with the below error message as "The system has not finished loading request 445315 into data target ZECC_C01". While creating index also it failed with error message as "Lock NOT set for: Generate index, RSSM_PROCESS_INDEX terminated, because InfoCube/DSO object ZECC_C01 could not be locked".
    Please help me in solving this issue.
    Thanks & Regards,
    Bharathi

    Hi,
    Manage the data target - ZECC_C01 and check the request number 445315. Also check the subsequent data targets if further loading was erroneous. Check whether the request is green / Properly loaded or not.
    You can also use RSBKREQUEST table to check the request and its corresponding data target.
    This request is either red or yellow caused this failure.
    Hope this helps.
    Regards,

  • What's the relation between SESCrawlerExport index and UCM index?

    Does the SESCrawlerExport index feeds on changes from the UCM indexer?
    What happens if the UCM->Admin Applets->Repository Manager->Indexer->Automatic Update Cycle is disabled.
    Can the SESCrawlerExport index recollect changes?
    Thanks
    @

    you are right!
    Is there a threshold? The sql which ran above threshold can be captured?
    and I try that:
    1. there are three sql scripts (loop 10, 10000, 100000000)
    anmh@MYORACLE> select sql_id,sql_text,bind_data from v$sql where sql_text like '%count%a2%';
    8hxar1zmt4p24
    begin for i in 1..10 loop select count(*) into :cnt from a2; end loop; end;
    akmfy8m24dhvf
    begin for i in 1..10000 loop select count(*) into :cnt from a2; end loop; end;
    51ugvw2ajg75m
    begin for i in 1..100000000 loop select count(*) into :cnt from a2; end loop; end;
    2. check in dba_hist_sqltext:
    (1) loop 100000000 :
    anmh@MYORACLE> select sql_id from dba_hist_sqltext where sql_id='51ugvw2ajg75m';
    SQL_ID
    51ugvw2ajg75m
    (2) loop 10000 :
    anmh@MYORACLE> select sql_id from dba_hist_sqltext where sql_id='akmfy8m24dhvf';
    SQL_ID
    akmfy8m24dhvf
    (3) loop 10 :
    anmh@MYORACLE> select sql_id from dba_hist_sqltext where sql_id='8hxar1zmt4p24';
    no rows selected
    It prove that Hemant is right.

  • Difference between btree index and bitmap index

    i knw btree is the default index.but what's are the other difference present.

    21 characters and 10 seconds at google:
    http://www.akadia.com/services/ora_bitmapped_index.html
    http://www.oracle.com/technology/pub/articles/sharma_indexes.html
    http://www.dba-oracle.com/art_9i_indexing.htm
    Dim

  • Primary index and secondary index in a select query

    Hii,
    How to use a primary or secondary  index in a select query?  How does this indexes actually work?
    Moderator message: please search for available information/documentation.
    Edited by: Thomas Zloch on Jan 21, 2012 8:38 PM

    rajan please just google or search SDN. there are large number of post for this..
    to give you a head start: for using a particular index in the select query a %_HINTS ORACLE 'INDEX clause is added

  • How do you differentiate between indexed and non-indexed prompts?

    Hi,
    I'm trying to fill Webi parameters dynamically, using the Webi REST SDK (4.1 SP04). This environment runs on top of SAP BW and uses BICS to connect to the BEx query.
    When the prompt is implemented as a BEx variable, the call to GET /biprws/raylight/v1/documents/{docid}/parameters will show @type: sapVariable, which tells me it requires the values to be passed as an ID and (optionally) their description.
    Prompts that are defined in the Webi query panel, return @type: prompt. This however doesn't indicate if they need the prompt value IDs or just their plain values.
    Example (JSON):
      "parameters": {
        "parameter": [
            "@dpId": "DP0",
            "@type": "prompt",
            "@optional": "false",
            "id": 2,
            "technicalName": "psTestPrompt",
            "name": "TestPrompt",
            "answer": {
              "@type": "Text",
              "@constrained": "false",
              "info": {
                "@cardinality": "Single",
                "lov": {
                  "@refreshable": "false",
                  "@hierarchical": "false",
                  "id": "UNIVERSELOV_DS0.DO1a6"
    In this case, I'll look at the value for @refreshable; if it's true, the prompt requires IDs, if false, just the plain values.
    It's only when a prompt does not have an LOV associated with it (disabled in the prompt properties, see screenshot below), I won't have the lov information when retrieving the parameter information and thus won't be able to determine whether to pass value IDs or just plain values.
    FYI, replying with prompt value IDs looks something like this:
      "parameters": {
        "parameter": [
            "id": 2,
            "answer": {
              "values": {
                "value": {
                  "@id": "000000123456",
                  "$": "123456"
    Plain values looks like this:
      "parameters": {
        "parameter": [
            "id": 2,
            "answer": {
              "values": {
                "value": 123456
    In short: how do I determine whether to pass values by ID or just their plain value given the prompt template retrieved through a GET /biprws/raylight/v1/documents/{docid}/parameters call?

    Hi Anthony,
    Just FYI, I've also noticed that when you have 2 BEx variables, and you only define 1 of them as a prompt (using the BEx variable window in the Webi Query Panel), the REST SDK will still report all of BEx variables as prompts, instead of the 1 variable that was checked as prompt.
    (this happens in BI 4.1 SP4 Patch 4)
    In the query panel:
    Uncheck Use BEx query defined default values at runtime
    Uncheck the Set as prompt checkbox for the second variable.
    REST SDK output for GET /biprws/raylight/v1/documents/{docid}/parameters?lovInfo=false :
      "parameters": {
        "parameter": [
            "@dpId": "DP0",
            "@type": "sapVariable",
            "@optional": "false",
            "id": 0,
            "technicalName": "ZMXXXX",
            "name": "XXXXX",
            "answer": {
              "@type": "Text",
              "@constrained": "true",
              "info": {
                "@cardinality": "Multiple",
                "lov": {
                  "@refreshable": "true",
                  "@hierarchical": "true",
                  "id": "UNIVERSELOV_DS0.:M:STR:ZMXXXX"
            "@dpId": "DP0",
            "@type": "sapVariable",
            "@optional": "false",
            "id": 1,
            "technicalName": "ZYYYYYY",
            "name": "YYYYYYYY",
            "answer": {
              "@type": "Text",
              "@constrained": "true",
              "info": {
                "@cardinality": "Multiple",
                "lov": {
                  "@refreshable": "true",
                  "@hierarchical": "true",
                  "id": "UNIVERSELOV_DS0.:M:STR:ZYYYYYY"

  • Average of all values between (first above and last above) a threshold value.

    Currently I have a VI which I programmed a year or more ago, which grabs any value out of a data set that is above a threshold value. This is used for capturing the average of all values over a threshold when there is one peak of values that go above that threshold. However, when there are two or more peaks that go above this threshold, only the values above that value are averaged, so the end result is the average of two or more averages.
    What I need is for every value that occurs after the threshold is reached and before the threshold is dropped below for the last time. Picturing a set of data whose graph looks like the letter "M," for example with the threshold being halfway up the M, I want to show the average of (the first hump, plus the dip below the humps, plus the last hump) but what I'm getting now is the average of (the first hump, plus the last hump). What I get now cuts out the data between the two peaks.
    Any assistance would of course be appreciated.
    Solved!
    Go to Solution.
    Attachments:
    AveAboveThresholdAll.vi ‏15 KB

    Actually I think that Tims solution has a little difference to the stated problem that both limits should be above a threshold value. Since the second array is inverted the rounding should be not towards +Infinity but towards -Infinity in order to really only go up to the last element that is above the threshold. The code as made by Tim takes one sample more, which could or couldn't have any significance.
    Nevermind, I take that back.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

Maybe you are looking for

  • I sync'd my iphone 4s and lost precious Voicemail messages

    These voicemails are precious to me because they were voicemails to me from my twin sister who passed away recently.  Is there anything I can do to get these back?  I now have an app to download them to the computer (phone view). Is there a way to re

  • Availability of Online Bill

    My online bill says that my next bill is due 24 december BUT apparently it takes 48 hours (YES 48 hours!!!!) for BT to upload a bill after it is "generated" (they probably use BT Broadband) so my next bill will not in fact be available to view until

  • Can iTunes Gift cards and iTunes Gifts be used as a payment method when setting up family sharing as an organizer ?

    i want to set up family sharing and i will be the organizer when setting up family sharing i am asked to use a valid payment method and i don't want to use any credit or debit cars so can i use iTunes Gift cards and iTunes Gifts as a payment method ?

  • How do I test if witchable graphics works?

    I bought a dv6-6135dx in the store and am going to return it and have ordered the same computer with the core i7 processor through HP.  I still have the AMD model and am wondering how I test to see if the switchable graphics is working as several pos

  • CC file saved in cs6, won't open with all layers in both versions

    Hello there, I really hope you could help me. Recently i designed a scetch in illustrator CC and saved it as usual (without extra options). Yesterday i worked on this same file in illustrator CS6, which i found acting weird but not paying attention a