Selection in JTable is being lost

Hello everybody,
I'm having the following problem, I have a JTable that is loaded through a viewobject when
I select some records in the JTable and I use the scroll bar in JScrollPane, the selection is reset to a single line,
could someone tell me how do I do to fix this.
thanks in advance.
I'm using JDeveloper Studio 11.1.1.2.0.
ADF Swing.

The table binding cannot really handle multi-selection, and there are situations (like the scrolling) where the table restores the (single) selection that the middle-tier can handle.
You might be able to create a special implementation of a ListSelectionModel.
When the user selects a row in the UI, the UI class calls JTable.changeSelection() while the JUTableBinding calls getSelectionModel() and then works with that directly.
In getSelectionModel() you might be able to return your special selection model class, that stores and handles the additionally selected row, wrapping the original selection model.
And when the table binding calls setSelectionInterval() on your wrapper while trying to restore the selection during scrolling, the wrapper adds your additionally selected rows and passes that to the selection model.
Haven't tried it that way yet, but something along those lines might work.
Sascha

Similar Messages

  • Multiple selection in JTable for deletion

    Dears,
    I'm using Jdeveloper 9.0.3.3 on 8.1.7 Oracle DB.
    I noticed that when a JTable is bound to a View object ==> only one row can be selected.
    My situation -which I think is very common- I have a screen with JTable where I can edit a row and commit my updates or select multiple selection in JTable and delete them at once ; thats what I need.
    It is very like the test of any application module but allow multiple selection and deletion in JTable for user's selected rows.
    How this could be done in JClient?
    Thankx in advance.

    Thanks for your suggestions! They both would work as workarounds, I think. I tried another way:
    Following code changes a TableBinding bound JTable's selection model to Multi select (thanks to Shailesh!!).
    void setMultiSelectionModel(JTable tbl)
    class MultiSelectionListListener implements javax.swing.event.ListSelectionListener
    ListSelectionModel defSelModel;
    MultiSelectionListListener(ListSelectionModel model)
    defSelModel = model;
    public void valueChanged(javax.swing.event.ListSelectionEvent e)
    if (!e.getValueIsAdjusting())
    ListSelectionModel listModel = (ListSelectionModel)e.getSource();
    int leadIndex = listModel.getLeadSelectionIndex();
    if (leadIndex == listModel.getAnchorSelectionIndex()
    && leadIndex == listModel.getMaxSelectionIndex()
    && leadIndex == listModel.getMinSelectionIndex())
    //change currency on the bound iterator only if
    //one row is being selected.
    defSelModel.setSelectionInterval(leadIndex, leadIndex);
    ListSelectionModel newModel = new DefaultListSelectionModel();
    newModel.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    newModel.addListSelectionListener(new MultiSelectionListListener(tbl.getSelectionModel()));
    tbl.setSelectionModel(newModel);
    This fixes the bug if you select some rows and then select a row before the first selected one. Seems to work great.

  • I am attempting to update students' iPads using the Apple Configurator software. However, information for 3rd party apps, like Notability and Explain Everything, is being lost.

    I am attempting to update students' iPads using the Apple Configurator software. However, information for 3rd party apps, like Notability and Explain Everything, is being lost.

    Mike,
    If by "still nothing" you mean they are not showing up in the AU manager after reinstalling them....
    Im guessing the AU Cache itself is now corrupted so.....
    Quit LPX
    Open Finder
    Press the option key and click "Go" in Finder's menu and select "Library". (This is the User Library and not the System Library and is normally hidden which is why you have to hold down the option key when clicking on Go.... to reveal it in the drop down menu that will appear)
    Go to "Caches" dir and remove "AudioUnitCache" dir.
    Now Restart your Mac.....
    and then Launch LPX and let it rescan your plugins and see if that fixes things....
    Fingers crossed...
    Nigel

  • CUBE detail rows being lost

    Hi,
    I have a problem where the lowest level of my CUBE is losing data and the aggregated levels are correct. My CUBE is sales dimensioned by assets, customer, geography and time. The lowest level of geography is branch, the previous level called area has the correct total but the branch level doesnt include all the rows.
    Is there a way to check the cube build, I dont get any errors during build.
    Any help appreciated,
    Brandon

    Hi again,
    I have made some inroads into my problem but am still without understanding of why this is happening. Basically I have found that when I choose to compress my CUBE then cells are being lost from my CUBE although their values are included in the aggregate levels above.
    So i re-created the CUBE with no compression and the lowest levels look correct BUT my CUBE now takes an hour where it used to take 20mins to refresh.
    So I have logged a SR with Oracle but wondered if anyone had any ideas why creating a compressed CUBE would “lose” cells with valid values ??
    This led me to thinking about sparsity of my CUBE and whether my definitions are correct and should I be trying to compress it in the first place. BTW , am using AWM 10.2.0.2a DB= 10.2.0.2
    I have 4 dimensions Asset, Customer, Time and Geography and my CUBE is just SALES at this stage.
    Is this a correct way of calculating the sparsity for each dimension and if so then what should my implementation details of my CUBE be :-
    SUMMARY :-
    TIME DIMENSION SPARSITY RATING = (TUPLES_WITHOUT_TIME * LEAF_VALUES) / TOTAL_TUPLES = (784046 * 12) / 1729961 = 5.4
    GROGRAPHY DIMENSION SPARSITY RATING = (TUPLES_WITHOUT_GEOGRAPHY * LEAF_VALUES) / TOTAL_TUPLES = (1604895 * 433) / 1729961 = 401.69
    ASSET RATING = (TUPLES_WITHOUT_ASSET * LEAF_VALUES) / TOTAL_TUPLES = (193253 * 176269 ) / 1729961 = 19690
    CUSTOMER RATING = (TUPLES_WITHOUT_CUSTOMER * LEAF_VALUES) / TOTAL_TUPLES = (1642 * 23494 ) / 1729961 = 22
    DETAILS :-
    1.) TIME DIMENSION
    -- tuples_full = 1729961
    select count(distinct to_char(fisc_month_id)||to_char(tbid_company_geography_id)||to_char(tbid_asset_id)||to_char(cus_customer_no))
    from bi_monthly_sales
    -- TIME Leaf Values leaf_values = 12
    select count(distinct(fisc_month_id)) from bi_time
    --tuples_without_time = 784046
    select count(distinct to_char(tbid_company_geography_id)||to_char(tbid_asset_id)||to_char(cus_customer_no))
    from bi_monthly_sales
    TIME DIMENSION SPARSITY RATING = (TUPLES_WITHOUT * LEAF_VALUES) / TOTAL_TUPLES = (784046 * 12) / 1729961 = 5.4
    2.) GEOGRAPHY DIMENSION
    -- tuples_full = 1729961
    select count(distinct to_char(fisc_month_id)||to_char(tbid_company_geography_id)||to_char(tbid_asset_id)||to_char(cus_customer_no))
    from bi_monthly_sales
    -- GEOGRAPHY Leaf Values leaf_values = 433
    select count(distinct(tbid_company_geography_id)) from bi_geography
    --tuples_without_geography = 1604895
    select count(distinct to_char(fisc_month_id)||to_char(tbid_asset_id)||to_char(cus_customer_no))
    from bi_monthly_sales
    GROGRAPHY DIMENSION SPARSITY RATING = (TUPLES_WITHOUT * LEAF_VALUES) / TOTAL_TUPLES = (1604895 * 433) / 1729961 = 401.69
    -- ASSET Leaf Values leaf_values = 176269
    select count(distinct(tbid_asset_id)) from bi_asset
    --tuples_without_assets = 193253
    select count(distinct to_char(tbid_company_geography_id)||to_char(fisc_month_id)||to_char(cus_customer_no))
    from bi_monthly_sales
    -- ASSET RATING = (TUPLES_WITHOUT * LEAF_VALUES) / TOTAL_TUPLES = (193253 * 176269 ) / 1729961 = 19690
    -- CUSTOMER Leaf Values leaf_values = 23494
    select count(distinct(customer_no)) from bi_customer
    --tuples_without_customer = 1642
    select count(distinct to_char(tbid_company_geography_id)||to_char(fisc_month_id)||to_char(fisc_month_id))
    from bi_monthly_sales
    CUSTOMER RATING = (TUPLES_WITHOUT * LEAF_VALUES) / TOTAL_TUPLES = (1642 * 23494 ) / 1729961 = 22
    Sorry for the long posting, any help appreciated.
    Cheers,
    Brandon

  • HT1212 i don't have the computer that my iPod was registered to and i forgot my password because i just found my phone after being lost for 2 years

    i don't have the computer that my iPod was registered to and i forgot my password because i just found my phone after being lost for 2 years. Idk what to do so i can access my ipod.

    Place the iOS device in Recovery Mode and then connect to your computer and restore via iTunes. The iPod will be erased.
    iOS: Wrong passcode results in red disabled screen                         
    If recovery mode does not work try DFU mode.                        
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings        
    For how to restore:
    iTunes: Restoring iOS software
    To restore from backup see:
    iOS: Back up and restore your iOS device with iCloud or iTunes
    If you restore from iCloud backup the apps will be automatically downloaded. If you restore from iTunes backup the apps and music have to be in the iTunes library since synced media like apps and music are not included in the backup of the iOS device that iTunes makes.
    You can redownload most iTunes purchases by:
    Downloading past purchases from the App Store, iBookstore, and iTunes Store        
    If problem what happens or does not happen and when in the instructions? When you successfully get the iPod in recovery mode and connect to computer iTunes should say it found an iPod in recovery mode.

  • How to do Multi Cell Selection in JTable

    Dear Friends,
    Any body know Multi cell selection in jtable......
    Thanks

    Try overriding the changeSelection(....) method of JTable.
    public void changeSelection(int row, int column, boolean toggle, boolean extend)
         if (d.after(currentDate)
              super.changeSelection(row, column, toggle, extend);
    }

  • Hi, I have a new laptop and would like to syncronise my iphone with iTunes (which I have installed again). But my old laptop has died so I could not transfer any media files, etc. Can I simply connect my iPhone to the laptop without any data being lost?

    Hi, I have a new laptop and would like to syncronise my iphone with iTunes (which I have installed again). But my old laptop has died so I could not transfer any media files, etc. Can I simply connect my iPhone to the laptop without any data being lost?
    Many thanks in advance!

    you have a new phone and a new comp and you want to restore to your old data ?!
    I can't think of anything but icloud, and what was purchased via itunes

  • HT1212 i just found my phone after it being lost for a month and it has a passcode on it that i dont remember how do i get it off without losing everything i have on it

    just found my phone after it being lost for a month and dont remember the passcode what do i do

    Maybe call Apple Corp/Security..................
    Presumably you can prove you are the Owner...

  • Is their way to prevent a form data from being lost when a validation fails

    Is their way to prevent a form data from being lost when a validation fails?

    So I would use APEX_COLLECTION (there is some information in APEX documentation).
    Read all data you need to keep after submit and save them to your collection. Then, if validation fails, show report with data not from base, but from your collection. You have to create process, which creates collection, and you need to modify your report definition to get data not only from DB but also from collection.
    If you have any questions feel free to ask.
    Regards,
    Przemek
    Edited by: Przemek on 2009-01-10 17:47

  • How to programatically select different JTable cells

    Dear all,
    I need to programatically select different JTable cells.
    I have to make the inverse selection. So if the user has a table of one column and 10 rows, and selects rows 3,6,8, the inverse selection should select all the other remainig cells and deselect 3,6, and 8.
    I tried using the following but it does not work ?
    for (int i = 0; i < table.getRowCount(); i++) {
    table.changeSelection(i, 0, true, false);
    Hope someone can help.
    Regards,
    Kanita

    Dear all,
    I need to programatically select different JTable cells.
    I have to make the inverse selection. So if the user has a table of one column and 10 rows, and selects rows 3,6,8, the inverse selection should select all the other remainig cells and deselect 3,6, and 8.
    I tried using the following but it does not work ?
    for (int i = 0; i < table.getRowCount(); i++) {
    table.changeSelection(i, 0, true, false);
    Hope someone can help.
    Regards,
    Kanita

  • When will the Blackberry os systems be avaliable without values being lost

    Windows 8 phone os helping with the free trial of Azure for servers but what about developer mode not being lost
    Is AMD responsible , will the steam network prove to be most valuable for floppy search solutions or are all media programs for a short trial not reaching any events.
    Apparently all data lost

    Mr. Jones,
    You are a real lifesaver!!!
    It worked on the Mac.  Will have to do some searches to find the same on the PC since the same is happening.
    Do you happen to know why Adobe is saying they are not compatible with Office 2011 now?  I found a link on the Adobe webite along those lines yesterday, but was not able to find it this morning to insert into this post.
    Our CEO had a real meltdown at about 2am the other morning when trying to pdf something for a meeting the next day.  Was not very pretty.
    THANK YOU!!!

  • HT4528 How can I erase an iphone remotely due to it being lost to prevent someone from using it?

    How can I erase an iPhone remotely due to it being lost to prevent someone from using it?

    You have to have had Find My iPhone active on the device before it was stolen, and it has to be connected to the Internet via wifi or cellular. Log into www.icloud.com and see if you can locate your device. If it is offline, it means it is probably out of battery, the thief has turned it off. You can send a wipe command to the phone and if it does get connected, it will wipe the phone. If you did not have Find My iPhone active, there is nothing you can do.

  • Multiple selection in JTable

    Hi ,
    The problem is to select multiple rows and columns in the JTable like that of a excel application and have the focus on the first column of the last row. for example if select cells from ( 1,1 ) to ( 4,4), after selection the focus should be in cell (4,1). i have written a prgram( which is below) which uses listSelection to find out the cells which are selected. i found out the cells which are selected also. but i do not know how to get the focus on that cell. i have attached the code below also.. i want to know whether there is any method which set the focus to the particular cell. Can the problem above can be solved in any other way..or a simpler way..
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    class myTable {
    public static void main(String a[] ) {
              JFrame myframe = new JFrame();
              JTable jtable = new JTable(10,10);
              jtable.setCellSelectionEnabled(true);
         // add the listener to the table
    ListSelectionModel listSelectionModel;
         OSSTableSelectionHandler obj = new OSSTableSelectionHandler(jtable,10,10);
         listSelectionModel = jtable.getSelectionModel();
    listSelectionModel.addListSelectionListener(obj);
         myframe.getContentPane().add(jtable);
         myframe.show();
    } // end of public static void main
    } // end of class of myTable
    class OSSTableSelectionHandler implements ListSelectionListener {
                   JTable table;
         int row;
                   int col;
    OSSTableSelectionHandler(JTable tab, int r, int c ) {
         table = tab;
    row = r;
              col = c;
    public void valueChanged(ListSelectionEvent e) {
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                   int i = 0,j = 0;
    int firstIndex = e.getFirstIndex();
    int lastIndex = e.getLastIndex();
    boolean isAdjusting = e.getValueIsAdjusting();
    if (lsm.isSelectionEmpty()) {
    System.out.println(" Selection empty ");
    } else {
    // Find out which indexes are selected.
                        int maxrow = 0 ;
    int minIndex = lsm.getMinSelectionIndex();
    int maxIndex = lsm.getMaxSelectionIndex();
    for ( i = minIndex; i <= maxIndex; i++) {
    if (lsm.isSelectedIndex(i)) {
                                  if ( maxrow < i )
                                       maxrow = i;
                                  for (j = 0;j < col ;j++ )
                                       if ( table.isCellSelected(i,j) )
                                            System.out.println("The selected index is " + i + " " + j);
                             } // end of if                    
    } // end of for
                   // after this maxrow contains the last row that has beeb selected
                   // this for loop is to find out the first column in the maxrow that is selected
                   for (j = 0;j < col ;j ++ )
                        if ( table.isCellSelected(maxrow,j) )
                                  break;
                   // set the focus to the column ( maxrow, j )
    } // end of else
    } // end of fucn value changed
    } // end of class OSSTableSelectionHandler

    Whic cell is focused depends on where you begin your selection. The cell that you press your mouse first will be the focused one. Here is how I implement the mutiple selection functionality in a JTable as what MS Excel provides. This class is independent of my any other package. your table has to have column headers and a upper left JLabel corner(int the scroll pane containing the table) in order to make this class which I named TableSelectionAdapter function properly. You can revise and imporve it as you need, however.
    package petrochina.riped.gui.table.tableadapter;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.awt.datatransfer.*;
    import java.util.*;
    * Enables multiple selection funtionality on <code>JTable</code>s.
    * @author Guanglin Du,SEC of Riped, PetroChina,
    * [email protected]
    * @version 1.0 2002/09/16
    public class TableSelectionAdapter extends MouseAdapter {
    private String newline = "\n";
    private boolean DEBUG = false;
    // private boolean DEBUG = true;
    private JTable myTable = null;
    private boolean shiftKeyDown = false;
    private boolean ctrlKeyDown = false;
    private int firstSelectedColIndex = -1;
    * Constructs with a <code>myTable</code> to simplify its reusability.
    * Guanglin Du, 2002/09/19
    * @param myTable     a <code>JTable</code>
    public TableSelectionAdapter(JTable myTable) {      
    this.myTable = myTable;
    initTableSelection();
    * The initTableSelection method: initializes the row/column/cell
    * selection functionality of the table.
    * Guanglin Du, 2002/09/19
    public void initTableSelection() {      
    getMyTable().setSelectionMode(
              ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
         //Cell selection
         myTable.addMouseListener(new MouseAdapter() {
         public void mousePressed(MouseEvent e) {
              myTable.setColumnSelectionAllowed(true);
              myTable.setRowSelectionAllowed(true);
         setMyKeyListener(); //shift/control key listener
         //column selection functionality
         JTableHeader myTableHeader = getMyTable().getTableHeader();
         myTableHeader.addMouseListener(new TableHeaderListener());
         //enalbles select-all functionality
         setSelectAllFunction();
    * This setSelectAllFunction isto set the select-all functionality
    * when the upper left corner label of the JTable is clicked.
    * Note: JTable's parent JScrollPane has to be found.
    * Guanglin Du, 2002/09/19
    public void setSelectAllFunction() {      
    Container firstParent = getMyTable().getParent();
    if (firstParent instanceof JViewport) {
         Container secondParent = firstParent.getParent();
         if (secondParent instanceof JScrollPane) {
         JScrollPane myScrollPane = (JScrollPane)secondParent;
         JLabel myLabel =
              (JLabel)myScrollPane.getCorner(JScrollPane.UPPER_LEFT_CORNER );
         myLabel.addMouseListener(this);
    * Detects shift/control key state.
    * DGL, 2002/09/18
    public void setMyKeyListener() {
         getMyTable().addKeyListener(new KeyAdapter(){               
         //keyPressed
         public void keyPressed(KeyEvent e){
              //shift key state
              if(e.isShiftDown())     shiftKeyDown = true;                    
              //control key state
              if(e.isControlDown()) ctrlKeyDown = true;
    //keyReleased
         public void keyReleased(KeyEvent e){
              //shift key state
              if( !e.isShiftDown() ) shiftKeyDown = false;                    
              //control key state
              if( !e.isControlDown() ) ctrlKeyDown = false;
    * Adds the table header listener to enable single/multiple column selection.
    * DGL, 2002/09/17
    public void setTableHeaderListener() {
         JTableHeader myTableHeader = myTable.getTableHeader();
         myTableHeader.addMouseListener(new TableHeaderListener());
    * Returns the <code>myTable</code> property value.
    * @return myTable the table that this class handles
    public JTable getMyTable() {
    return myTable;
    * Sets <code>myTable</code> property value of this class.
    * @param myTable the table that this class handles
    public void setJTable(JTable myTable) {
         this.myTable = myTable;
    * Returns the shiftKeyDown property value.
    * @return boolean, Guanglin Du, 2002/09/18
    public boolean getShiftKeyDown(){
         return shiftKeyDown;
    * Return the ctrlKeyDown property value.
    * @return boolean, Guanglin Du, 2002/09/18
    public boolean getCtrlKeyDown(){
         return ctrlKeyDown;
    * This inner class handles the column selection, the same
    * behavior as MS Excel.
    * Guanglin Du, 2002/09/18
    class TableHeaderListener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {    
         stopLatestCellEditing(); //To save the data being edited
         if(DEBUG) System.out.print("mousePressed on ");
         JTableHeader myColumnHeader = (JTableHeader)e.getSource();
         Point myPoint = e.getPoint();
         int selectedColIndex = myColumnHeader.columnAtPoint(myPoint);
         if(DEBUG) System.out.print("the header of column "
              + selectedColIndex+newline);
         JTable table = myColumnHeader.getTable();
         //The following column selection methods work only if these
         //properties are set this way
         table.setColumnSelectionAllowed(true);
         table.setRowSelectionAllowed(false);
         int myRowCount = table.getRowCount();
         //makes this table focused, so that setMyKeyListener method can
         //listen for shift/control KeyEvent
         table.requestFocus();
    //     System.out.println("myRowCount = " + myRowCount);
         if( getShiftKeyDown() ){
         table.clearSelection();
         table.setRowSelectionInterval(0,myRowCount-1);
         table.setColumnSelectionInterval(selectedColIndex,selectedColIndex);
         if(firstSelectedColIndex > -1) {
              table.addColumnSelectionInterval(firstSelectedColIndex, selectedColIndex);
              firstSelectedColIndex = -1;//restore to -1
         } else if( getCtrlKeyDown() ) {
         table.addRowSelectionInterval(0,myRowCount-1);
         table.addColumnSelectionInterval(selectedColIndex,selectedColIndex);
         } else {
         table.clearSelection();
         table.setRowSelectionInterval(0,myRowCount-1);
         table.setColumnSelectionInterval(selectedColIndex,selectedColIndex);
         if(DEBUG) System.out.println("shiftKeyDown = " + shiftKeyDown
              +";"+" ctrlKeyDown = " + ctrlKeyDown);     
         //saves the first selected column index
         firstSelectedColIndex = selectedColIndex;
    * MouseAdapter implemenation.
    * mousePressed: sets the select-all functionality
    * when upper left corner label of the table is clicked
    * Guanglin Du, 2002/09/18
    public void mousePressed(MouseEvent e) {    
         if(DEBUG) System.out.println("Select all");
         stopLatestCellEditing();//To save the data in editing
         getMyTable().selectAll();
    * Triggers the latest <code>ActionEvent</code> in a table cell to save
    * the latest data. Or, the newly input data will not be stored into the table
    * model and cannot be retrieved.
    public void stopLatestCellEditing() {
    int editingRow = getMyTable().getEditingRow();
    int editingCol = getMyTable().getEditingColumn();
    if (editingRow != -1 && editingCol != -1){
         TableCellEditor cellEditor =
         getMyTable().getCellEditor(editingRow, editingCol);
         cellEditor.stopCellEditing();
    Here is how you can use it in your coding(where myTable is a JTable instance you create):
         /* Adds TableSelectionAdapter to enable all kinds of selection action. */
         TableSelectionAdapter tableSelect = new TableSelectionAdapter(myTable);     

  • Problem in cell selection in JTable Java Swing

    hii
    I am using JTable that shows data from database. I have developed one functionality. I change one cell value and then select multiple cell. If I press F12 function key then it copies first selected value and past it to another selected cells. it is working properly but when I press F12 it sets the last selected cell in editable mode. I want that all cell which has been pasted should be selected (with default blue colour not in editing mode). I am using ListSelectionListener for JTable Cell Selection and KeyListener for F12 functionality.
    Please give some solution
    I can not override editCellAt Method because i have already extended JFrame. and i tried to do this with Jtable.getSelectedColumn and getSelectedRow it is displaying the same value, by this how can I get the particular area of selection means Row nd Column Selected.
    How would I know the current selection when user selects more than one cell???
    Thanks
    Edited by: 850979 on 11-Apr-2011 02:13
    Edited by: 850979 on 11-Apr-2011 03:59

    camickr wrote:
    Presumably, JTable installs an action for the F12 key that results in starting editing the last selected cell.
    There are no bindings for F12. See the [url http://www.camick.com/java/blog.html?name=key-bindings]Key Bindings listing. (...)
    Right.
    Of course it doesn't make sense that a F? key should invoke the editorI thought he meant F2 ("edit" on Windows), so that sounded natural.
    All KeyEvents are passed to the editor for the cell and the editor is psuedo invoked. That is, the caret is not placed on the text field used as the editor, but the character typed is added to the editor. You can then either use tab/enter to save the text or use the escape key to cancel the editing.Thanks for the explanation. I had never noticed (I kept on double-clicking my JTable cells when I wanted to edit them! :o)
    Of course it doesn't make sense that a F? key should invoke the editor, but this is a by product of all KeyEvents being forwarded so you don't have to have special Key Bindings for every character.You're right - as always.
    They (Sun) could have filtered out some of the keys such as those, though, because as noted by the OP the current behavior is unintuitive.
    To better control when the cell is editable based on the KeyEvent you can override the table with code like <snipped>
    As you suggested using a Key Binding will prevent this behaviour as well (but only for that key).Right again, but in this specific case that is acceptable (the developer wants to attach a specific behavior to a specific key only).
    OP here is an SSCCE of that second approach:
    public class TestKeyBindingsOnJTable {
        public static void main(String... args) {
            final DefaultTableModel dtm = new DefaultTableModel(new String[] {"A", "B"}, 0);
            dtm.addRow(new String[]{"A1", "B1"});
            dtm.addRow(new String[]{"A2", "B2"});
            dtm.addRow(new String[]{"A3", "B3"});
            JTable table = new JTable(dtm);
            table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), "clear");
            table.getActionMap().put("clear", new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    dtm.removeRow(0);
            JOptionPane.showMessageDialog(null, table);
    }Edited by: jduprez on Apr 8, 2011 9:36 PM

  • JTable cell being edited after model changed.

    I have a fairly simple JTable, with a implementation of AbstractTableModel supplying the data. The cells are edited by using a JComboBox. I wrap these into a DefaultCellEditor. I have a KeyListener attached to the JTable listening for VK_DELETE, and when it finds one, instructs the model to delete the row represented by the selected row in the table.
    Everything works fine until I want to delete a row from the table. My scenario is:
    - I click in a cell, and the editor opens.
    - I select an entry in the list. The editor closes, the result is rendered, and the wee yellow box around the cell is shown
    - I hit the delete key.
    - My key listener picks up the event, and informs the model to delete the row. I remove the row from the model and invoke fireTableDataChanged().
    The result is that the row is deleted, but the table ends up with the cell editor deployed on the cell of the row below (which is now at the same row as the one I just deleted).
    My tracing shows that the isCellEditable is called on the model after the delete. I don't know why.
    Can anyone explain how to prevent this or what might be causing the table to think that the cell needs editing?
    Thanks, Andrew

    It will do whatever is the default. I wrap the JComboBox in a DefaultCellEditor. I can't see how the editor is involved at this point, or why the editor becomes involved after the row has been deleted.
    Remember, at the time that I hit the delete key, there is no editor rendered or visible. I have the JTable displayed, a row selected, and the yellow box around one of the (editable but not currently being edited) cells. This has been achieved by editing a cell (displaying the cell editor - a combo box) and selecting an entry. The editor is removed, and the cell displayed with the (default) cell renderer for the table.
    The delete action is caught by the listener on the table, the model is instructed to delete a row from its underlying data, which fires a fireTableDataChanged event.
    That is all I do. After that it is all swing. The table model starts getting asked about cells being editable after I have finished deleting the row. I'll post the relevant code below if that helps.
    The datamodel is of class ConstraintTableModel (see below) and the column model is of class DefaultTableColumnModel
    JTable table = new JTable( dataModel, columnModel );The column model is defined liike so:
    columnModel = new DefaultTableColumnModel();
    TableColumn labelColumn = new TableColumn(ConstraintTableModel.LABEL_COLUMN);
    labelColumn.setHeaderValue( dataModel.getColumnName(ConstraintTableModel.LABEL_COLUMN));
    labelColumn.setPreferredWidth( 5 );
    labelColumn.setMaxWidth( 5 );
    labelColumn.setResizable( false );
    TableColumn taskColumn = new TableColumn(ConstraintTableModel.TASK_COLUMN);
    taskColumn.setHeaderValue( dataModel.getColumnName(ConstraintTableModel.TASK_COLUMN));
    TableColumn typeColumn = new TableColumn(ConstraintTableModel.TYPE_COLUMN);
    typeColumn.setHeaderValue( dataModel.getColumnName(ConstraintTableModel.TYPE_COLUMN));
    columnModel.addColumn( labelColumn );
    columnModel.addColumn( taskColumn );
    columnModel.addColumn( typeColumn );I add the key listener like so:
    table.addKeyListener( new KeyAdapter()
        public void keyPressed( KeyEvent e )
          if( e.getKeyCode() == KeyEvent.VK_DELETE )
            log.debug("Delete pressed in listener attached to table ");
            JTable t = (JTable) e.getSource();
            int selectedRow = t.getSelectedRow();
            if( selectedRow >= 0 )
              log.debug("  Removing row " + selectedRow);
              ((ConstraintTableModel)t.getModel()).removeRow(selectedRow);
            log.debug("Finished with key press");
      } );The cell editor is created like this:
    JComboBox taskEditorComponent = new JComboBox( tasksModel );
    taskEditorComponent.setFont( GanttChart.tableFont );
    taskEditorComponent.setBackground( Color.WHITE );
    DefaultCellEditor taskEditor = new DefaultCellEditor(taskEditorComponent);
    taskEditor.setClickCountToStart( 1 );
    table.setDefaultEditor( GanttTask.class, taskEditor );The model is coded like so:
    class ConstraintTableModel extends AbstractTableModel
        // Constants
        public static final int LABEL_COLUMN = 0;
        public static final int TASK_COLUMN = 1;
        public static final int TYPE_COLUMN = 2;
        private Vector          columnNames;
        private ArrayList       dataRows;
        public ConstraintTableModel()
            super();
            this.buildDataVector();
            this.addPrimerRow();
         * Every row in the table is a GanttConstraint. Therefore when deciding what to
         * display in any particular column of the table, we need to determine what the
         * column is, and then use the informatino in the GanttConstraint to go out to the
         * lookup and get the relevant object, and value to display.
        public Object getValueAt( int row, int col )
            Object          returnObject = "";
            GanttConstraint aConstraint = (GanttConstraint) this.getDataRows().get( row );
            // We're rendering the task column. If there's no task id (partially filled in row)
            // return blank otherwise return the master task
            else if( col == ConstraintTableModel.TASK_COLUMN )
                if( aConstraint.getMasterId() != null )
                    GanttTask masterTask = (GanttTask) real.getLookup().get( aConstraint.getMasterId() );
                    returnObject = masterTask;
            // We're rendering the type column. If there's no type (partially filled in row)
            // return blank otherwise return the constraint type
            else if( col == ConstraintTableModel.TYPE_COLUMN )
                if( aConstraint.getType() != null )
                    GanttConstraintType constraintType = (GanttConstraintType) GanttConstraintType.getConstraintTypes()
                                                                                                     .get( aConstraint.getType()
                                                                                                                      .intValue() );
                    returnObject = constraintType;
            return returnObject;
         * When we receive this message, we are handed an object of the type specified in
         * getColumnClass. We need to take this object and place the relevant information into
         * the GanttConstraint row in the table model.
         * Depending on whether the row being modified is an existing row or a new row, set
         * the state of the constraint appropriately.
         * @see javax.swing.table.TableModel#setValueAt(java.lang.Object, int, int)
        public void setValueAt( Object value, int row, int col )
            log.debug( "+setValueAt (row/col) " + row + "/" + col );
            if ( value == null )
                log.debug( "  handed a null value. Returning" );
                return;
            GanttConstraint aConstraint = (GanttConstraint) this.getDataRows().get( row );
            // If we are modifying the primer row, add another primer row.
            if( row == ( this.getRowCount() - 1 ) ) // Last row is always the primer
                log.debug( "  adding a primer row" );
                this.addPrimerRow();
            // We're modifying the Task data. Get the GanttTask handed to us and place it
            // into the master slot in the constraint.
            if( col == ConstraintTableModel.TASK_COLUMN ) // Task
                log.debug( "  updating the master task" );
                GanttTask selectedTask = (GanttTask) value;
                aConstraint.setMaster( selectedTask );
            // We're modifying the Type data. Get the GanttConstraintType handed to us and place it
            // into the type slot in the constraint.
            if( col == ConstraintTableModel.TYPE_COLUMN ) // Constraint type
                log.debug( "  updating the constraint type" );
                GanttConstraintType selectedConstraintType = (GanttConstraintType) value;
                aConstraint.setType( selectedConstraintType.getType() );
            log.debug( "-setValueAt" );
        public Class getColumnClass( int col )
            Class columnClass = super.getColumnClass( col );
            if( col == ConstraintTableModel.LABEL_COLUMN )
                columnClass = String.class;
            if( col == ConstraintTableModel.TASK_COLUMN )
                columnClass = GanttTask.class;
            if( col == ConstraintTableModel.TYPE_COLUMN )
                columnClass = GanttConstraintType.class;
            return columnClass;
        // We are handing the data storage
        public void setDataRows( ArrayList dataRows )
            this.dataRows = dataRows;
        public boolean isCellEditable( int row, int col )
            log.debug( "+isCellEditable (row/col) " + row + "/" + col );
            if( !real.canEdit() )
                return false;
            if( ( col == ConstraintTableModel.TASK_COLUMN ) ||
                    ( col == ConstraintTableModel.TYPE_COLUMN ) )
                return true;
            else
                return false;
        // We are handing the data storage
        public ArrayList getDataRows()
            return this.dataRows;
        public String getColumnName( int column )
            return (String) this.getColumnNames().get( column );
         * Clean up rows that do not have both the master task and type set. Not interested in them
        public void removeDirtyRows()
            log.debug( "+removeDirtyRows" );
            Iterator dataIterator = this.getDataRows().iterator();
            while( dataIterator.hasNext() )
                GanttConstraint element = (GanttConstraint) dataIterator.next();
                if( ( element.getMasterId() == null ) || ( element.getType() == null ) )
                    element.setTransient();
                    dataIterator.remove();
            fireTableDataChanged();
            log.debug( "-removeDirtyRows" );
        public void removeRow( int row )
            log.debug( "+removeRow(" + row + ")" );
            if( row < this.getDataRows().size() )
                GanttConstraint aConstraint = (GanttConstraint) this.getDataRows().get( row );
                this.getDataRows().remove( row );
                if( aConstraint.isClone() )
                    aConstraint.setDeleted();
                else
                    aConstraint.setTransient();
                    getClone().removeConstraint( aConstraint );
                fireTableDataChanged();
            if( this.getRowCount() == 0 )
                this.addPrimerRow();
            log.debug( "-removeRow" );
        public void clearRow( int row )
            log.debug( "+clearRow(" + row + ")" );
            if( row < this.getDataRows().size() )
                GanttConstraint aConstraint = (GanttConstraint) this.getDataRows().get( row );
                aConstraint.setMasterId( null );
                aConstraint.setType( null );
                fireTableRowsUpdated( row, row );
            log.debug( "-clearRow" );
        public int getColumnCount()
            return getColumnNames().size();
        public int getRowCount()
            return dataRows.size();
         * The table will be filled with constraints relevant to 'clone'.
        private void buildDataVector()
            ArrayList  data = new ArrayList( 1 );
            Collection allConstraints = getClone().getStartConstraints();
            allConstraints.addAll( getClone().getEndConstraints() );
            Iterator constraintIter = allConstraints.iterator();
            while( constraintIter.hasNext() )
                GanttConstraint element = (GanttConstraint) constraintIter.next();
                if( element.getType().equals( GanttConstraint.START_SPECIFIED ) ||
                        element.getType().equals( GanttConstraint.FINISH_FROM_DURATION ) )
                    continue;
                else
                    data.add( element );
            this.setDataRows( data );
        private Vector getColumnNames()
            if( columnNames == null )
                columnNames = new Vector( 3 );
                columnNames.add( " " ); // Needs space otherwise all the headers disappear
                columnNames.add( "Task" );
                columnNames.add( "Constraint" );
            return columnNames;
        private void addPrimerRow()
            log.debug( "+addPrimerRow" );
            // Create a constraint for the 'clone' task. Set it as transient until validation
            // where we will deal with it if necessary.
            GanttConstraint primer = new GanttConstraint( real.getLookup() );
            primer.setObjectId( chart.getNextUniqueId() );
            primer.setTransient();
            primer.setSlave( getClone() );
            primer.setProject( getClone().getProject() );
            getClone().addConstraint( primer );
            this.getDataRows().add( primer );
            int lastRow = this.getRowCount() - 1;
            fireTableRowsInserted( lastRow, lastRow );
            log.debug( "-addPrimerRow" );

Maybe you are looking for

  • My iTunes will NOT open ( no error )

    When I go to open my iTunes, the icon changes for a second ( looks like a sheet of paper or something ) and changes back. The hourglass shows up for about a second, and then it quits. iTunes never starts up. Ever. I have tried using the suggestions i

  • Applications not appearing in iTunes

    The applications purchased on my dad's 3GS iphone won't transfer to his iTunes even though the PC is "authorised". Does anyone know how to fix this problem?

  • Default Audio Interface

    Is it possible to make an external audio interface the default output interface for the entire system, not just a specific program like Logic? I would like to use monitors that obviously will not connect into the standard 1/8th jack, and would need t

  • Help...How to Play Video and Auido using windows media player in developer forms?

    I am using the Windows NT workstation and Oracle Forms6i, I want to know how to use window media player in oracle forms? I have insert an OLE object and add Windows media player as an control object, but I don't know how to play the audio and video.

  • How to see what happens in a code??

    In a class I have this method:     public boolean sameName(Person other)     return  getName().equals(other.getName());   }Is there someway that I can get a print of the return statement when I run the code with arguments? I thought of something like