Selection in a Sorted JTable

If this has already been answered, let me know; I couldn't find anything like it in my search.
I have an application that displays a JTable of the rows in a database table. The table is pure wizard code except that I overrided the isCellEditable() method so the user couldn't edit the cells. My problem is that when the user clicks on a table heading and the table is sorted, row selection is turned off. If the heading is clicked again and the sort disabled, the rows become selectable again.
Any ideas on a solution?

Hey Jan,
I found a solution posted by Frank Nimphius that is easier to implement
Since we do server-side sorting we don't need the client-side sorting provided as default.
Add this code to remove this default behavior
MouseListener[] mls = jTable1.getTableHeader().getMouseListeners();
          for (int i = 0; i < mls.length; i++)
               if (mls.getClass().toString().indexOf("oracle.jbo.uicli.jui.JUTableSortModel")>-1)
                    jTable1.getTableHeader().removeMouseListener(mls[i]);
This way your table will not be editable, sortable and selectable after a sort.
Regards
Johan
Original source: http://forums.oracle.com/forums/thread.jspa?messageID=918000&#918000

Similar Messages

  • Sort JTable

    I have a JTable with data in it.
    The table has 5 columns.
    The first column is a column with numbers and I want that if the header of column 1 is clicked it sorts the table.
    I found a lot of things about sorting a table but I don't exactly understand them.
    Can someone tell me how it works??

        // table model for listing selected genes.
        selectTM = new AbstractTableModel( ){
          public int getColumnCount( )
              { return 2;}
          public int getRowCount( )
              { return selected.size(); }
          public Object getValueAt( int r, int c )
              { return c == 0 ? selected.get( r ).id() : selected.get( r ).type(); }
          public String getColumnName( int c )
              { return c == 0 ? "Gene Id" : "Annotation"; }
          public boolean isCellEditable( int r, int c )
              { return false; }
        // table for listing selected genes.
        final JTable table = new JTable( selectTM );
        table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
        // sorting based on column header clicked.
        final JTableHeader header = table.getTableHeader();
        header.setReorderingAllowed( false );
        header.addMouseListener( new MouseAdapter( ){
          public void mousePressed( MouseEvent me )
            int col = header.columnAtPoint( me.getPoint( ) );
            if( col >= 0 ){
              if( col == 0 )
                selected.sortById();
              else
                selected.sortByType();
              selectTM.fireTableDataChanged();
        } );

  • How to delete the selected rows in a JTable on pressing a button?

    How to delete the selected rows in a JTable on pressing a button?

    You are right. I did the same.
    Following is the code where some of them might find it useful in future.
    jTable1.selectAll();
    int[] array = jTable1.getSelectedRows();
    for(int i=array.length-1;i>=0;i--)
    DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
    model.removeRow(i);
    }

  • In iPhoto if I select View, then Sort Photos by title, how do I stop it reverting to sorting by date when I close iPhoto and re-open it later?

    In iPhoto if I select View, then Sort Photos by title, how do I stop it reverting to sorting by date when I close iPhoto and re-open it later?

    In what mode, Events, Photos or in an Album, are you when you select View ➙ Sort ➙ By Title?
    As a first fix attempt try the following:
    1 - delete the iPhoto preference file, com.apple.iPhoto.plist, that resides in your
         User/Home/Library/ Preferences folder.
    2 - delete iPhoto's cache file, Cache.db, that is located in your
    User/Home/Library/Caches/com.apple.iPhoto folder (Snow Leopard and Earlier).
    or with Mt. Lion from the User/Library/Containers/com.apple.iPhoto/
    Data/Library/Caches/com.apple.iPhoto folder
    3 - launch iPhoto and try again.
    NOTE 1: If you're moved your library from its default location in your Home/Pictures folder you will have to point iPhoto to its new location when you next open iPhoto by holding down the Option key when launching iPhoto.  You'll also have to reset the iPhoto's various preferences.
    NOTE 2:  In Lion and Mountain Lion the Library folder is now invisible. To make it permanently visible enter the following in the Terminal application window: chflags nohidden ~/Library and hit the Enter button - 10.7: Un-hide the User Library folder.
    OT

  • To change the font of a selected row in a Jtable

    Hello,
    Is it possible to change the font of a selected row in a jtable?
    i.e. if all the table is set to a bold font, how would you change the font of the row selected to a normal (not bold) font?
    thank you.

    String will be left justified
    Integer will be right justified
    Date will be a simple date without the time.
    As it will with this renderer.Only if your custom renderer duplicates the code
    found in each of the above renderers. This is a waste
    of time to duplicate code. The idea is to reuse code
    not duplicate and debug again.
    No, no, no there will be NO duplicated code.
    A single renderer class can handle all types ofdata.
    Sure you can fit a square peg into a round hole if
    you work hard enough. Why does the JDK come with
    separate renderers for Date, Integer, Double, Icon,
    Boolean? So that, by default the rendering for common classes is done correctly.
    Because its a better design then having code
    with a bunch of "instanceof" checks and nested
    if...else code.This is only required for customization BEYOND what the default renderers provide
    >
    And you would only have to use instanceof checkswhen you required custom
    rendering for a particular classAgreed, but as soon as you do require custom
    renderering you need to customize your renderer.
    which you would also have to do with theprepareRenderer calls too
    Not true. The code is the same whether you treat
    every cell as a String or whether you use a custom
    renderer for every cell. Here is the code to make the
    text of the selected line(s) bold:
    public Component prepareRenderer(TableCellRenderer
    renderer, int row, int column)
    Component c = super.prepareRenderer(renderer, row,
    , column);
         if (isRowSelected(row))
              c.setFont( c.getFont().deriveFont(Font.BOLD) );
         return c;
    }It will work for any renderer used by the table since
    the prepareRenderer(...) method returns a Component.
    There is no need to do any kind of "instanceof"
    checking. It doesn't matter whether the cell is
    renderered with the "Object" renderer or the
    "Integer" renderer.
    If the user wants to treat all columns as Strings or
    treat individual columns as String, Integer, Data...,
    then they only need to override the getColumnClass()
    method. There is no change to the prepareRenderer()
    code.
    Have you actually tried the code to see how simple it
    is?
    I've posted my code. Why don't you post your solution
    that will allow the user to bold the text of a Date,
    Integer, and String data in separate column and then
    let the poster decide.Well, I don't see a compilable, runnable demo anywhere in this thread. So here's one
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Arrays;
    import java.util.Date;
    import java.util.Vector;
    public class TableRendererDemo extends JFrame{
        String[] headers = {"String","Integer","Float","Boolean","Date"};
        private JTable table;
        public TableRendererDemo() {
            buildGUI();
        private void buildGUI() {
            JPanel mainPanel = (JPanel) getContentPane();
            mainPanel.setLayout(new BorderLayout());
            Vector headerVector = new Vector(Arrays.asList(headers));
             Vector data = createDataVector();
            DefaultTableModel tableModel = new DefaultTableModel(data, headerVector){
                public Class getColumnClass(int columnIndex) {
                    return getValueAt(0,columnIndex).getClass();
            table = new JTable(tableModel);
    //        table.setDefaultRenderer(Object.class, new MyTableCellRenderer());
            table.setDefaultRenderer(String.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Integer.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Float.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Date.class, new MyTableCellRenderer());
            JScrollPane jsp = new JScrollPane(table);
            mainPanel.add(jsp, BorderLayout.CENTER);
            pack();
            setLocationRelativeTo(null);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        private Vector createDataVector(){
            Vector dataVector = new Vector();
            for ( int i = 0 ; i < 10; i++){
                Vector rowVector = new Vector();
                rowVector.add(new String("String "+i));
                rowVector.add(new Integer(i));
                rowVector.add(new Float(1.23));
                rowVector.add( (i % 2 == 0 ? Boolean.TRUE : Boolean.FALSE));
                rowVector.add(new Date());
                dataVector.add(rowVector);
            return dataVector;
        public static void main(String[] args) {
            Runnable runnable = new Runnable() {
                public void run() {
                    TableRendererDemo tableRendererDemo = new TableRendererDemo();
                    tableRendererDemo.setVisible(true);
            SwingUtilities.invokeLater(runnable);
        class MyTableCellRenderer extends DefaultTableCellRenderer{
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                 super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                if ( isSelected){
                    setFont(getFont().deriveFont(Font.BOLD));
                else{
                    setFont(getFont().deriveFont(Font.PLAIN));
                if ( value instanceof Date){
                    SimpleDateFormat formatter =(SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.MEDIUM);
                    setText(formatter.format((Date)value));
                if(value instanceof Number){
                   setText(((Number)value).toString());
                return this;
    }Hardly a "bunch of instanceof or nested loops. I only used the Date instanceof to allow date format to be specified/ modified. If it was left out the Date column would be "18 Apr 2005" ( DateFormat.MEDIUM, which is default).
    Cheers
    DB

  • The columns of a selected row in a JTable

    Hello guys,
    I am trying to loop through the columns of a selected row in a JTable. Any ideas how i can do that?
    Thanks in advance for your replies.
    Antana.

    there is getValueAt(int row, int column) method in JTable.
    will this help you?
    and please post swing related queries to swing forum.
    --Azodious_                                                                                                                                                                                                                                                                                                           

  • How to select a row in Jtable at runtime

    how to select a row in Jtable at runtime.

    use
    setRowSelectionInterval(int fromRowIndex, int toRowIndex);example if your table has 10 rows then u want to select the rows from 4 to 8 then use
    setRowSelectionInterval(3, 7);if you want to select just one row for example 5 then use
    setRowSelectionInterval(5, 5);

  • Problem with select all cells in JTable

    Hi guys! I get some problem about selecting all cells in JTable. I tried to used two methods:
    1> table.selectAll()2> changeSelection(firstcell, lastcell,false,true)
    firstcell:[0,0], lastcell[rowcount-1,colcount-1]
    Result: only the first row selected when i use both methods.
    Note: i set up the selection model as following:
    this.dataSheet.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                    this.dataSheet.setCellSelectionEnabled(true);
                    this.dataSheet.setRowSelectionAllowed(true);
                    this.dataSheet.setColumnSelectionAllowed(true);Thanks !

    What selection properity should be changed in order to enable selectAll() method work properly? Is there Any constraints? Here is the TableModel I am using. And i set up selection mode use the following code:
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setCellSelectionEnabled(true);
    table.setRowSelectionAllowed(true);
    table.setColumnSelectionAllowed(true);
    import java.util.Vector;
    import javax.swing.table.*;
    import javax.swing.JTable;
    public class DataSheetModel extends AbstractTableModel{
              private Vector data = new Vector();//Store data
              private Vector columnNames = new Vector();//Store head
              public DataSheetModel(){}
              public DataSheetModel(Vector headVector, Vector dataVector){
                   if(headVector != null) this.columnNames = headVector;
                   if(dataVector != null) this.data = dataVector;
              public int getColumnCount(){
                   return columnNames.size()+1;
              public int getRowCount(){
                   return data.size()+1;
              public String getColumnName(int col){
                   if(col==0) return "";
                   else return (String)columnNames.get(col-1);
              public Object getValueAt(int row, int col){
                   if(col==0) {
                        if(row != data.size()) return String.valueOf(row);
                        else return "*";
                   else{
                        if(row != data.size()){
                             Vector rowVector = (Vector)data.elementAt(row);
                             return rowVector.elementAt(col-1);
                        }else return null;
              public void setValueAt(Object value, int row, int col){
                   if(row != this.data.size()){
                        Vector rowVector = (Vector)data.elementAt(row);
                        rowVector.set(col-1,value);
                        this.data.set(row,rowVector);
                        this.fireTableDataChanged();
                   }else{
                        Vector rowVector = new Vector();
                        for(int i=0; i<this.getColumnCount()-1; i++) rowVector.add(null);
                        rowVector.set(col-1,value);
                        this.data.add(rowVector);
                        this.fireTableDataChanged();
              public Class getColumnClass(int c){
                   return getValueAt(0,c).getClass();
              public boolean isCellEditable(int row, int col){
                   if(col == 0) return false;
                   else return true;
              public void setDataVector(Vector head, Vector data){
                   if(head != null) this.columnNames = head;
                   if(data != null) this.data = data;
    }

  • How to select a row in JTable for right mouse click ?

    Hi All,
    I need to select a row on JTable for right mouse click ?
    Can any one help me ?
    Thanks a lot.
    Seelam.

    Got solution...
    tabel.addRowSelectionInterval(..) works.
    thanks.

  • Sort jTable rows by column as Integer value

    Hi all,
    I have problem with sort jTable rows. I have some columns and in first are integer data. jTable sort that as String value..1,10,11,12....2,21, ...
    How can I do that?
    Thanks

    In the future, please post Swing questions to the Swing forum: http://forum.java.sun.com/forum.jspa?forumID=57
    What does the TableModel's getColumnClass method return for that column?

  • Sorting JTable using keyboard

    Hi all,
    Is it possible to sort JTable using keyboard? There is a key to get the focus to a column header by clicking the key F8. I don't find any key to sort the table based on the column which is in focus. Is there any solution for this?
    Thanks,
    Ganesh

    You miss the point of that link, there is no need to write any custom code.
    I have already tried to implement Keyboard listener of JTableHeader which must be similar to using Key Bindings.You should NOT use a KeyListener, Swing was designed to use KeyBindings
    The problem I am facing is that I am unable to find the column which got the key strokeYou don't have to write any code, the functionality you want is already supported with a Key Binding. Just use the "space" key.
    If you don't like the space key, then you can assign the Action to any other KeyStroke. The link shows you how to do that in 3-4 lines of code.

  • Getting the Selected Row from a JTable

    hi,
    how Can i get the Selected row from a JTable
    thanks...

    You know that JTable class? Well, you see those methods in it called "getSelectedRow()" and "getSelectedRows()"...?

  • How do I change the colour of a selected cell in a jTable?

    I have a Jtable that displays URL names in one column. There are several problems I'm having. The effect I'm trying to achieve is this:
    When the user runs the mouse over the URL name the cursor should change into a hand (similar to what happens in an HTML hyperlink). I'm aware that the Cursor class can set the cursor graphic so i figure that i need a listener of some sort on each cell (so the cursor can change from an arrow to a hand) and also one to indicate when the cursor is not on a cell (so that it can change from a hand back into an arrow). Is this the right track?
    Also, I've looked at the DefaultTableCellRenderer class (which, as i understand it, is responsible for how each cell in the jtable is displayed) for a method that will allow me to set the background of a selected cell (or row or column). I require this because each time i select a cell (or row) it becomes highlighted in blue. I would rather it just remained white and changed the cursor to a hand. I know there exists a method for setting the background for an unselected cell but none for a selected cell. Again, I'm not sure if I'm going down the right track with this approach.
    Lastly, if the cell has been selected (by a mouse click) the font of the writing in the cell (i.e. The name of the URL) should change. This shouldn't be too much of a problem I think.
    I do not expect anyone to provide code to do all of this but some general pointers would be extremely helpful as I do not know if I'm thinking on the right track for any of this. Having some (limited) experience with Swing I doubt there is a simple way to do this but I can only hope!
    Thanks.
    Chris

    http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
    there you can find some examples with CellRenderer's and so on ...
    have fun

  • Showing selected row after sorting

    I have big JTable with lots of columns. Selection of row is highlighted
    using some background color. Sorting is also provided on TableHeader.
    After selecting some row, when user does the sorting, this selected row
    goes outof visible view of table.
    My requirement is to show the same selected row again after doing sorting. I was thinking of calling method like setSelectedRow(), but
    unfortunately there is nothing like this method.
    I was also thinking of using AccessibleJTable, but couldnt go
    anywhere.
    Is there any way to do this?
    Thanks in advance.
    Anup

    I have big JTable with lots of columns. Selection of row is highlighted
    using some background color. Sorting is also provided on TableHeader.
    After selecting some row, when user does the sorting, this selected row
    goes outof visible view of table.
    My requirement is to show the same selected row again after doing sorting. I was thinking of calling method like setSelectedRow(), but
    unfortunately there is nothing like this method.
    I was also thinking of using AccessibleJTable, but couldnt go
    anywhere.
    Is there any way to do this?
    Thanks in advance.
    Anup

  • Inserting a Row to a Specific Position in a  Sorted JTable

    Hello,
    I am currently writing an application that will be a network alerting tool. Periodically it will query a database, and if alerts are found, display them on a JTable for a user to see. However, my problem is the following. If the user sorts the table by a column, new alerts are entering the table in their sorted position. This could cause the table to rearrange and be confusing to the user, also causing them to possibly miss alerts. So, what I would like to happen is that new alerts get inserted at the top of the table, while all previous alerts will stay in their sorted order. For example, say alerts received in the order D A C B . The user then sorts the table, so that the alerts are now in the order A B C D. If alert E comes in, I want the table to show as E A B C D. Then, if the user sorts again, the table would become A B C D E, and so on.
    I have attempted multiple ways to achieve this. My most recent being using the table.setRowSorter(null), inserting into the model, and then re-enabling sorting. However, switching to null appears to make all the rows go back to their previously unsorted position. Any help would be greatly appreciated as to what I am missing.

    You can implement your own RowSorter, such that rows that have been added since the latest explicit sort are ranked first (override RowSorter.rowsInserted() to know them).
    You'll have to override methods convertRowIndexToModel(int) and convertRowIndexToView(int) . This is easy if you used the rowsInserted() events to, e.g., maintain one atrribute latestUnsortedRow.

Maybe you are looking for

  • Applescript works in Automator, but not when app is opened - running all if statements at once?

    Good evening, I am new to applescript and have a newbie question regarding the following code. I am making a simple automator program to pull songs from iTunes to practice dancing to. I've started the program with a script that lets the user choose w

  • Very Basic Question about Entity Beans !!!  Need your help.

    Hi, I have the following requirement:- ============================== There is an application A, whose multiple instances can run at the same time. There is some data/variable which is to be globally shared (i.e by all the instances). I have thought

  • Canon MP 600  I cant print

    I have the airport extreme...green lights and all...however, i cannot print wirelessly...i keep getting an error 9672....according to Canon this is because printer is not meant to work wirelessly....apple says it is a vendor issue... Please help...I

  • Picture albums somehow deleted from iPhone...

    I somehow had old camera roll pictures from previous iPhones backed up onto my current iPhone. My guess is that during a back up, I somehow accidentally backed up all of the pics on that computer onto my phone. I actually found it very annoying that

  • Cl_xml_document and type RAW on Unicode systems?

    Cheers guys, I'm using a cl_xml_document for exporting data from but000 to an XML file. Works fine, except for the PARTNER_GUID which seems to be interpreted as chars (it's raw bytes), eg. the GUID "0E1E1FFCF746D14CADEF2D3EBEAEB21B" becomes "Dh4f/PdG