Sorting JTable column with DefaultTableModel

Hi all,
can i sort the column in Jtable which is using the DefaultTableModel? If can, how? I have downlaad the TableSorter.java and implement it into my code which is using DefaultTablemodel, but it doesn't work... :(
If sort does not work with the DefaultTableModel, which model should i use that will list the records in the JTable and sort it?
Thanks in advance for yr help...

When you create your own table model you usually extend the AbstractTableModel class, and the DefaultTableModel class does just the same.
So I think your problem is likely to be due to the sorter class itself, rather than the model.
I hope this will help you.
Bye

Similar Messages

  • Sort order column with a between filter

    Hi all,
    [using OBI-EE version 10.1.3.3.1]
    I've got a column 'BLOCK_ROW' which contains values A,B,C....AA,AB,AC...BA,BB...FK,FL
    Alphabetically this orders A,AA,AB.... which is incorrect. The order should be A,B,C...
    To be able to sort correctly we added a column 'ROW_SORT' to our model, which is numeric. This column is set as the 'sort order column' in the repository and makes sure the sorting is done correctly.
    So far, so good...
    Now, I want to be able to use a 'between' filter on this column, e.g. between 'A' and 'C'. Unfortunately this returns A,B,C,AA,AB... while I want it to return A,B,C.
    Is this possible?
    Thanks,
    Elio
    Generated SQL:
    select distinct T91353.BLOCK_ROW as c1,
    T91353.ROW_SORT as c2
    from
    <table_name> T91353
    where ( T91353.BLOCK_ROW between 'A' and 'C' )
    order by c2
    --> Sorting handled based on ROW_SORT, between filter not :(

    That will only do the trick in this particular example. Between 'A' and 'AA' will fail again and only returns A and AA while it should return A..Z and AA.
    Using extra filters is always possible but I'm looking for a more robust solution, which also allows for dashboard 'between' prompts based on this column.
    A workaround I came up with is to add a calculated field which concats an '_' in front of the single 'digit' values. This results in: A,B,_C,.....,AA,AB....FL. This set can be ordered alphabetically and this will work for now.
    In the future, however, it might happen that the order of the letters will completely change. In the datamodel this can be achieved by changing the order of the numbers in ROW_SORT.
    Example dataset:
    BLOCK_ROW | ROW_SORT
    Q | 1
    D | 2
    F | 3
    AA | 4
    A | 5
    The filter 'between D and AA' should then result in D,F,AA.
    Any suggestions?
    Thanks,
    Elio

  • Single JTable Column with several diff Cell Editors

    Am trying to create a single JTable column that can have several different cell editors. Java seems to be bias to having 1 cell editor for the whole column.
    For example in 1 column can I have
    Row1 : TextBox
    Row2: Check Box
    Row3: Radio Buttons
    Row4: JColorChooser
    At the moment I can only have one CellEditor for the whole column which is not very helpful.

    the default implementation offers to provide editors per column in the tableColumn and/or editors per class type by setting default editors ( JTable.setDefaultEditor(Class class, TableCellEditor editor) ). If you look at the getCellEditor method of JTable you see that first the tablecolumns are asked for an editor, and if this doesnt succeed a default editor for the class acording to the value at the passed grid position is determined.
    If this does not fullfil your needs, you can still overwrite the getCellEditor method of JTable and return whatever editor is suitable.
    regards,
    stefan

  • Sort JTable columns except one.

    Hi.
    I want make a sortable JTable, but I need to avoid the sorting by first column.
    There is an easy way to do it ??
    Thanks in advance
    Is solved. Thanks anyway.
    Message was edited by:
    DiegoJ

    hai,
    be too specific. dont think that ur ques has to be short. type more about ur question and make us clear to clear ur doubt. please type how the record will be before ur program get executed and how the answer has to be after ur program has to be executed. that is show them as u showed the records before.
    by
    bvrk.

  • Sorting on columns with templated Report -- Named Column (row template)

    Hi forum,
    I'm trying to duplicate a regular report's column sorting functionality in a "Named Column" report.
    The column headers are in the "Before first and after last row text" "Before Rows" area of the template :
    <th onClick="sortByColumn('#REGION_ID#',5)">Frequency</th>invoking this javascript:
    function sortByColumn(regionId,colNo) {
         var u = "f?p=124:401:&SESSION.:fsp_sort_" + colNo + "::RP&fsp_region_id="+regionId.substring(1);
           document.location.href=u;
    }I'd like to sort descending when a user clicks the column again, and to display the column sort arrows (up/down).
    However, since sorting is persisted per user, even when the page's cache is cleared, it would be necessary to pick up the sort column and order (ascending,descending) on page load or query it later using ajax, so that the sort display (the arrows) stays in synch with the actual sort.
    Has anyone got an idea how to do this?
    Cheers
    Edited by: YT on Apr 1, 2009 4:19 PM
    Edited by: YT on Apr 1, 2009 4:24 PM
    Edited by: YT on Apr 1, 2009 4:26 PM

    Hi,
    Sort ordering on reports are stored as user preferences - see Need to do column SORTING only when I click the column heading for Denes' example on how to use this
    Andy

  • JTable column with multiple components

    Hi,
    I have to use a List and a comobobox in a single column. How can i achieve this. It will be a great help if somebody can provide me some sample code.
    I know how to set a custom component for the entire column or entire row. So please provide me the code that may explain how can i add two different components to the single column?
    Thanks

    If it is display only, use cell renderer.
    If you do I/O or event dispatching, use cell editor.
    A Jpanel containing JList and JComboBox would be the component they return.
    Smells bad design, though.

  • Help with JTable column width

    Hi,
    I'm trying to resize my JTable columns with this code, but it's not working. What I am doing wrong?
    for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
    TableColumn tc = table.getColumnModel().getColumn(i);
    int width = (i == 0)? 10 : table.getWidth()/2 - 10; // three columns
    tc.setPreferredWidth(width);
    Thanks,
    Andr�

    Now my problem is that using either of these methods
    is they don't carry the user's selected column width
    through updates.It sounds like the change event your table model is firing is causing the entire table to be rebuilt. I would guess that you are firing fireTableStructureChanged() which would cause the entire table to be rebuilt (columns, cell values, etc.) Just fire a change event for the minimum necessary. If you can't identify what data in your table has changed (to fire cell or row change events), but the structure (columns) of the table hasn't changed, just fire fireTableDataChanged(). This will cause the cells to be redrawn with the new values, but shouldn't cause the columns to be rebuilt and resized.

  • Export JTable Column headers to Excel document

    Hello all!!! I am having a small problem while trying to export some data from a jTable to an excel document.
    I have a jTable and I use a custom TableModel with this:
    private String[] columnNames = {"First", "Second", "Third", "Forth"};as names for each column of the table.
    The thing I am trying to do is to export exactly the same "headers" from the columns of the jTable to the excel spreadsheet using Jakarta POI. Unfortunately I don't know how to do it and I haven't found anything yet on this forum. Can anyone help me with this?
    In simple words I want to know how I can have the same headers from my jTable columns, with the headers from the excel doument I will create.
    Many thanks in advanve!!!
    Kostas

    Thank you for your reply first of all. The problem is how to get the heading text and how to put it to the excel's first row OR to excels "headings" (if it is possible...). [in other words replace A,B,C,D from the excel document with the headers I get from the jTable...] .
    I hope now you can see what I am looking for... If there is no solution to this please tell me what are the alternatives. (B) could be a good example.
    Thanks you very much!!
    Kostas

  • JTable column Class  (getColumnClass)

    I create table model extended it from AbstractTableModel.
    by overwriting getColumnClass in model.
         @SuppressWarnings("unchecked")
         public Class getColumnClass(int c) {
              return getValueAt(0, c).getClass();
         }but I have problem with TableRowSorter. I implement my own Comparator interface for TableRowSorter, Which
    can compare column with Number and String or Boolean and String etc. ( String("") in cell with Number sense cells NULL value )
    I passing my comparator to
    TableRowSorter.setComparator(column, comparator);I have some number of comprators for String,Number and Boolean comparision.
    If i call sorting of column with Number values
    and columns first cell (0,0) contain String("") ( NULL value )
    my code logic automatically set
    TableRowSorter.setComparator(0, new StringComparator());but really column contains Number values with one String("") value.
    right code must be
    TableRowSorter.setComparator(0, new NumberComparator());how to determine column Class in right way???

    thanks everyone !!! I find solution :) I must create global Comparator for Object type and merge all different type comparators in to one ObjectComparator

  • F2 key not working with custom JTable Column

    I have a custom JTable Column (which is a JPanel with a JTextfield and JButton). Everything works as expected, except when the user presses "F2" to start editing the custom column cell. When the user presses F2, the custom cell goes into editing mode, but I am unable to type anything in it.
    Below is the SSCCE.
    Steps to Reproduce problem:
    1) Run the Program
    2) Select any cell in first Column.
    3) Press "F2" and try to type into the cell. Can't type anything.
    package com.ns;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.util.EventObject;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    public class TextButtonCellFrame extends javax.swing.JFrame {
        // Variables declaration - do not modify                    
        private JTextField inputText;
        private JScrollPane jScrollPane1;
        private JPanel testPanel;
        private JTable testTable;
        // End of variables declaration                  
        public TextButtonCellFrame() {
            initComponents();
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            testPanel = new JPanel();
            jScrollPane1 = new JScrollPane();
            testTable = new JTable();
            inputText = new JTextField();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            testTable.setModel(new DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            testTable.setCellSelectionEnabled(true);
            testTable.setRowHeight(52);
            testTable.setSurrendersFocusOnKeystroke(true);
            testTable.getColumnModel().getColumn(0).setCellRenderer(new MyTableCellRenderer());
            testTable.getColumnModel().getColumn(0).setCellEditor(new MyTableCellEditor(new JTextField()));
            testTable.getColumnModel().getColumn(0).setPreferredWidth(200);
            jScrollPane1.setViewportView(testTable);
            testPanel.add(jScrollPane1);
            inputText.setPreferredSize(new Dimension(50, 20));
            testPanel.add(inputText);
            getContentPane().add(testPanel, BorderLayout.CENTER);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-576)/2, (screenSize.height-417)/2, 576, 417);
        }// </editor-fold>                       
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TextButtonCellFrame().setVisible(true);
        public class MyTableCellRenderer extends JPanel implements TableCellRenderer {
            Point point;
            JButton button1 = new JButton("Test 1");
            JTextField txtField = new JTextField();
            public MyTableCellRenderer() {
                setLayout(new BorderLayout());
                this.add(button1, BorderLayout.EAST);
                this.add(txtField,BorderLayout.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
                if (isSelected) {
                    txtField.setBackground(testTable.getSelectionBackground());
                    txtField.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
                else {
                    txtField.setBackground(testTable.getBackground());
                    txtField.setBorder(null);
                return this;
        public class MyTableCellEditor extends DefaultCellEditor {
            JPanel panel = new JPanel();
            JButton button1 = new JButton ("Test 1");
            JTextField txtField;
            MyTableCellEditor(JTextField txtField) {
                super (txtField);
                this.txtField = txtField;
                panel.setLayout(new BorderLayout());
                panel.add(button1, BorderLayout.EAST);
                panel.add(txtField,BorderLayout.CENTER);
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == button1)
                    JOptionPane.showMessageDialog(null, "Action One Successful");
            public Component getTableCellEditorComponent(JTable table, Object value,
                                        boolean isSelected, int row, int column) {
                return panel;
           public boolean isCellEditable(final EventObject anEvent) {
              if (anEvent instanceof KeyEvent) {
                 final KeyEvent keyEvent = (KeyEvent) anEvent;
                 SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                       if (!Character.isIdentifierIgnorable(keyEvent.getKeyChar())) {
                          txtField.setText(txtField.getText() + keyEvent.getKeyChar());
                       txtField.setCaretPosition(txtField.getText().length());
                       txtField.requestFocusInWindow();
                return super.isCellEditable(anEvent);
    }The code for isCellEditable(final EventObject anEvent) which is needed to edit the cell using keyboard was provided by DarrylBurke here
    regards,
    nirvan.

    The F2 key when pressed generates an action event (either JTable generates it or some other component). I am not sure how to handle the action event in the isCellEditable() method. Also, F(X) range of keys other than F2 dump some junk character in the JTextfield when pressed. I am now stuck at this point and don't know how handle F(X) range of keys.
    regards,
    nirvan.

  • Jtable column sorting

    Hi all,
    I have jtable wirh setAutoCreateRowSorter(true); . The columns with Double object are sorting correctly. One column values are object of our class "Carat". But this column is not sorting like numbers. What are the changes I have to do to sort like number or Double.?
    my custom class Carat is
    import java.io.Serializable;
    import common.Common;
    public class Carat implements Serializable{
         private static final long serialVersionUID = 7876408747596231364L;
         Double carat;
         public Carat(double carat){
              this.carat = new Double(carat);
         public double doubleValue(){
              return carat.doubleValue();
         public void setCarat(Double carat){
              this.carat = carat;
         //here round to 3 decimal
         public String toString(){
              return Common.roundCarat(carat.doubleValue());
         public Double getDoubleValue(){
              return carat;
         public Carat getDifference(Carat cat){
              return new Carat(this.carat.doubleValue() - cat.doubleValue());
         public boolean equals(Carat cart){
              if(this.carat.doubleValue() == cart.doubleValue()){
                   return true;
              return true;
         public int compareTo(Carat anotherDouble) {
            return Double.compare(carat.doubleValue(), anotherDouble.doubleValue());
    }Ant suggestions ...plz help....

    You have to implement the Compareable-Interface.
    Also the compareTo-Implementation is wrong:
    use Object for the parameter type.
    public class Carat implements Serializable, Compareable {
    public int compareTo( Object that ){
    }Read the book Java "Effective Java" :)
    IMHO this post is not in the correct thread...

  • 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?

  • Is there any way to do a mass copy and paste of song titles from the "name" column to the "sort name" column? I know it can be done with individual titles but I have over 6,000 titles in my library.

    In iTunes, is there any way to do a mass copy and paste of song titles from the "name" column to the "sort name" column? I know it can be done with individual titles but I have over 6,000 titles in my library.

    Thank you. I have heard of Logic Pro 7, but I have never personally used it. I'm still growing in the world of Composition, and I know that it is something I will be studying in one of my Computer Music classes coming up for my degree. I think it is something I will look into getting once I can justify the price of it. I guess for the time being, I will continue to play and grow in my ability to use and take advantage of GB, and then see what I can do about or with Logic Pro when I'm ready. The thought of spending $1000 for a program is hard to bite, because I've already spent a lot to produce my music, not only electronic music, but also chamber music and so on. I had no idea it would be so expensive to dive deep into the world of composition! lol.
    Finale 2007: $500
    Sibelius 4: $500
    Jam Packs: $400
    Midi Keyboard Interface: $100
    PowerBook: $1700
    Printer for printing scores and analysis: $150
    Logic Pro 7: Oy!
    As you can see it adds up very quickly...that doesn't even include my personal instruments and study materials.
    Thank you for your input, as I haven't really worked much with LP, and therefore didn't know which features are available. I will talk with some of my Composition buddies, and professors and see what they have to say as well, and who knows, I may be able to get the express version through one of them.

  • 'Sort order column' doesn't work for prompt with function

    I turned on the 'sort order column property' in repository for a logic column 'school year', so when I get school year from prompt, it shows desc order. It works fine if th colume in prompt is a simple prompt. But when I add function in the column in prompt (means edit Fx with a case statement), when school year prompt shows in dashboard, it is not sorted in desc order any more, it went back to acs.
    Am I missing something, or this is a bug?
    Another question, when I turn on 'sort order column property' in repository for a logic column, can I choose to desc on another column? I couldn't do it, and had to create another sorting column.
    Thanks,
    Amy

    Cant you create this logic in the rpd and then apply order there and use the newly created column in your prompt..

  • Custom sort pivot table columns with Essbase as the data source

    Is it possible to sort columns in a pivot table according to an arbitrary value that I define when the data is coming from Essbase?
    For example, say I have a dimension called Soda, with values Coke, Diet Coke, Dr. Pepper and Diet Dr. Pepper. I create a report with a sales measure with the measure labels on the rows and the Soda dimension on the column. By default the columns will be sorted alphabetically:
    Coke Diet Coke Diet Dr. Pepper Dr. Pepper
    Sales 1M .5M .75M 1.25M
    I want to create a report that looks like this:
    Coke Diet Coke Diet Dr. Pepper Dr. Pepper
    Sales
    I think I could do this if the source was relational just by creating bins or creating a custom column with a case statement that assigns each Soda an arbitrary value and then sort on this value. Everything I've tried with Essbase as the source, though, results in:
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 42043] An external aggregate is found in an outer query block. (HY000)
    Any ideas?

    Hi,
    1. You can try solve the 'An external aggregate is found in an outer query block' by changing aggregation rule for your measure both in physical and business layer.
    By default it's set to Aggr_External - change it to Sum
    In physical : Column properties->Aggregation rule
    In business model : Column properties->Aggregation tab -> Default aggregation rule.
    This may change the result - after changing check whether you still get correct values.
    2. Also, in case the desired order is the same as the order of members in the Essbase cube, and you want to leave Aggr_External, you can create a calculated column that will help you with the sort.
    See http://oraclebizint.wordpress.com/2008/04/28/oracle-bi-ee-101332-handling-sort-order-in-hyperion-essbase-931-evaluate-and-mdx/
    Hope this helps,
    Alex

Maybe you are looking for

  • Can not install device driver in Windows 8.1

    I can not install driver of my webcam(Odyssey OD 202) windows 8.1 (upgraded from windows 8) The USB webcam is shown in Device manager. When I attempt to update driver and search for it automatically it shows the following message.

  • Generated lists not working in HTML conversion

    Using FM 8.0p277 I have been asked to convert a book to HTML for the first time. When I do this, FM crashes with an error log that I cannot locate in the Program Files folder, as indicated in the error message. I believe it is the generated files tha

  • User defined function - error at runtime

    Hi, I have to write a small java mapping, which has to obtain a substring 1 to 4 characters from a 5 characters string. I used <b>graphical</b> mapping and the following <b>java</b> mapping program <i>try if(NodeId.length() == 5) NodeId = NodeId.subs

  • Report Background Engine takes long time

    Hi all, I'm using Reports6i while the db is a 10gXE instance. When I click for the report, I see RBE starts but nothing happens for about 2-3 minutes; also in task manager I see RBE doesn't use CPU. After those minutes, ther parameter form appears. E

  • CCMS monitor, BPE is red

    In CCMS monitoring RZ20, the node XI_system Business Process Engine -> Overall status -> Status of the automatic customizing is red. The text is BPE customizing not fully maintained. When clicking this text, an information page is shown, and you can