Add ‘count #’ column to JTable

Posted by admin | Posted in Code Snippets, General Programming, Graphics And Design, Learning Materials | Posted on 05-02-2010

0

Important note first: This is mostly not my code, I was strugling with this problem for some time, I couldn’t google it at all, and one day, I’ve just found it. Now I use it in one of my projects but I cannot find the original post again, therefore I have decided to post it on my blog (slightly modified version of the original) so other people with similar problem will have a better chance of finding the solution.
So, the idea is very simple. The whole point of displaying additional column which is kind of independent from the other columns is to simply use another table. This way you can sort one table by column and the number column will not sort with it. – thats exactly what I was looking for and I guess its kind of popular problem.
Becouse you put two tables in one scroll pane the gui looks like its just one column!


I have created one simple method to apply this technique to any tables in my application (I use JXTable actually but JTable will do as well)

private void addLPColumn(JXTable table, JScrollPane scp){
        JTable rowTable = new RowNumberTable(table);
        scp.setRowHeaderView(rowTable);
        scp.setCorner(JScrollPane.UPPER_LEFT_CORNER, rowTable.getTableHeader());
        scp.repaint();
    }


RowNumberTable is simple one column table displaying the ‘count’ number of rows in the second table.


public class RowNumberTable extends JTable
    implements ChangeListener, PropertyChangeListener
{
    private JTable main;

    public RowNumberTable(JTable table)
    {
        main = table;
        main.addPropertyChangeListener( this );

        setFocusable( false );
        setAutoCreateColumnsFromModel( false );
        setModel( main.getModel() );
        setSelectionModel( main.getSelectionModel() );

        TableColumn column = new TableColumn();
        column.setHeaderValue("Lp.");
        addColumn( column );
        column.setCellRenderer(new RowNumberRenderer());

        getColumnModel().getColumn(0).setPreferredWidth(40);
        setPreferredScrollableViewportSize(getPreferredSize());
    }

    @Override
    public void addNotify()
    {
        super.addNotify();

        Component c = getParent();

        //  Keep scrolling of the row table in sync with the main table.

        if (c instanceof JViewport)
        {
            JViewport viewport = (JViewport)c;
            viewport.addChangeListener( this );
        }
    }

    /*
     *  Delegate method to main table
     */

    @Override
    public int getRowCount()
    {
            if(main != null)
                return main.getRowCount();
            else
                return 0;
    }

    @Override
    public int getRowHeight(int row)
    {
        return main.getRowHeight(row);
    }

    /*
     *  This table does not use any data from the main TableModel,
     *  so just return a value based on the row parameter.
     */

    @Override
    public Object getValueAt(int row, int column)
    {
        return Integer.toString(row + 1);
    }

    /*
     *  Don't edit data in the main TableModel by mistake
     */

    @Override
    public boolean isCellEditable(int row, int column)
    {
        return false;
    }
//
//  Implement the ChangeListener
//
    public void stateChanged(ChangeEvent e)
    {
        //  Keep the scrolling of the row table in sync with main table

        JViewport viewport = (JViewport) e.getSource();
        JScrollPane scrollPane = (JScrollPane)viewport.getParent();
        scrollPane.getVerticalScrollBar().setValue(viewport.getViewPosition().y);
    }
//
//  Implement the PropertyChangeListener
//
    public void propertyChange(PropertyChangeEvent e)
    {
        //  Keep the row table in sync with the main table

        if ("selectionModel".equals(e.getPropertyName()))
        {
            setSelectionModel( main.getSelectionModel() );
        }

        if ("model".equals(e.getPropertyName()))
        {
            setModel( main.getModel() );
        }
    }

    /*
     *  Borrow the renderer from JDK1.4.2 table header
     */

    private static class RowNumberRenderer extends DefaultTableCellRenderer
    {
        public RowNumberRenderer()
        {
            setHorizontalAlignment(JLabel.CENTER);
        }

        public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
        {
            if (table != null)
            {
                JTableHeader header = table.getTableHeader();

                if (header != null)
                {
                    setForeground(header.getForeground());
                    setBackground(header.getBackground());
                    setFont(header.getFont());
                }
            }

            if (isSelected)
            {
                setFont( getFont().deriveFont(Font.BOLD) );
            }

            setText((value == null) ? "" : value.toString());
            setBorder(UIManager.getBorder("TableHeader.cellBorder"));

            return this;
        }
    }
}

count_jtable_column

In my case the ‘count’ column is called ‘Lp.’ – in polish



I have created one simple method to apply this technique to any tables in my application (I use JXTable actually but JTable will do as well)

private void addLPColumn(JXTable table, JScrollPane scp){
        JTable rowTable = new RowNumberTable(table);
        scp.setRowHeaderView(rowTable);
        scp.setCorner(JScrollPane.UPPER_LEFT_CORNER, rowTable.getTableHeader());
        scp.repaint();
    }


Emergent Design: The Evolutionary Nature of Professional Software Development

Posted by admin | Posted in Learning Materials | Posted on 04-09-2008

0


Well, I have just read another comment left on my blog and I had realized, well, I had realized that I have a blog :) . Completly forgot about its existence, and since last post I was writing as a student at University of Greenwich, London, now I’m writing as an owner of a really small startup software company in Elblag, Poland :) , things change quickly.

Anyway, student or not, I still read a lot, maybe not that much as I used to do but stil quite a lot. I have decided to write a short note on the latest book I read as I’ve found it really interesting.

The title you know already, this book is not about programming but about more general concepts, about programming as a profession. It’s a nice book about software design and life as a software developer. Once you become proficient in any programming language and you start being interested in methodologies, patterns etc you should read this book!
Highly recommended!

Head First Software Development completed!

Posted by admin | Posted in Learning Materials | Posted on 01-03-2008

1

Another example of the book proving that software books can be fun! Head First series books are usualy easy to read and thats what makes them most valuable for me. I have read a few of them, since I started learning how to program, and I was never disappointed, I think I have read HF Servlets and JSP about 3 times :) and I know that if I start a project with Servlets or JSPs I will read a few bits again :) .
HF Software Development is of course no exception. This book on my bookshelf is a result of my new subscription to Safari, I should actualy say it’s on my virtual bookshelf :) .
I belive there are experienced software developers which will find this book boring or maybe not bringing anything new to their ‘toolbox’.
For me this book is superb! In my opinion every CS student should read it before going into the wild and look for a job.
This is in short what you can get:

  • A feel of profesional software development process
  • Reason for manager’s daily headache :)
  • What is TDD and how it works
  • What is Continous Integration
  • How tos: gathering requirements, desing and implement
  • A few bits on proper design, UML and refactoring
  • Many others which I either considered common knowledge or haven’t notice :)

Go to Safari books online or Amazon for detailed table of contents.
I would give it 5/5 mark.
Highly recommended

Mythical Man Month On My Bookshelf

Posted by admin | Posted in Learning Materials | Posted on 27-01-2008

0


I was reading so often about this one on the net and in other books that it was on top of my reading list quite a long time. I had no idea what to expect from this book and I haven’t found there anything what recently I like the most, like tips on software development, refactorings to patterns or code tunning. Well it’s non of those things but of course it’s not the author’s fault. Definietly I should do some more research before buying this one, as I think this book is not for startups in software industry like me. I belive, people who manage projects and people resources enjoy reading this book much more than those who write software only.
I cannot say I didn’t like it though, overall is always nice to read about such a huge project like soft for IBM mainframe.
Maybe not really what I’m looking for these days but definietly valuable read!
Recommended!

Code Complete on my bookshelf

Posted by admin | Posted in Learning Materials | Posted on 10-01-2008

1


Another Amazon’s 5 star rating book on my bookshelf. I have just finished this huge, over 800 pages, heavy as hell book. Well, in my opinion, it could be less than 300 or maybe even 200 pages, as most of it is so obvious that I just couldn’t belive someone has written book about it, hmmnn, maybe I’m wrong and maybe lots of people find it usefull, but still for me just 3 stars ;) .
What I have gained from reading this book? For sure I have stronger muscles on my back as I did carry it on the tube almost everyday :) , but beside that this book is of course not that bad and at the end of the day I would say it was a valuable read. I have enjoyed especially the chapter about code improvemens like refactorings and tuning and that is less than 150 pages! The rest, well, I think it’s good to brush up on some things a bit but if you have written a program with, lets say, at least 500 lines of code you are completly aware what correct intedation, comments, naming variables etc means not only for other people reading your code but especially to you!
One very good thing about this book is the fact that the author included tonnes of references to other books and research papers – heh, reading will never stop!

Kris on Joel

Posted by admin | Posted in Learning Materials | Posted on 10-12-2007

0


Another fantastic? book on my bookshelf – “Joel on Software: And on Diverse and Occasionally Related Matters That Will Prove of Interest to Software Developers, Designers, and Managers, and to Those Who, Whether by Good Fortune or Ill Luck, Work with Them in Some Capacity” by J.Sposlky. Well, I’m still not sure why this book gets so high marks on amazon web site but I’m sure of one thing about it – this book is fun. I did enjoy reading it although some bits were really pis..ng me off (like calling all people who work in McDonald’s ‘morons’) . Some people say don’t buy it – you can read it free on the web, but I definietly prefer printed version.
It is difficult to find anything bad said about Microsoft in this book and some articles touching Unix/Linux world seem to be unfair or mostly outdated but it is still nice to read Joel’s opinions even if we don’t agree with them every time.
This guy for sure has a lots of experience and for the beginner like me it’s nice to read through someone else IT career.
Again HR (Highly Recommended) :)

My Bookshelf!

Posted by admin | Posted in Learning Materials | Posted on 01-12-2007

0

Starting from now on I have decided to add to my blog entries of the books read by me recently.

First one is probably the thinnest and nicest to read ever. If you are interested in developing your programming skills beyond java, how things are in your neighbourhood, go ahead and read ‘Beyond Java’ by Bruce A. Tate.
I found this book really interesting. It moved in me some old, not touched for a long time cogs, the machine which pushed me into software development, need of discovering new things. I have realized that I need to improve not only for a bit better CV but mainly for fun, for those things all of us do programming.
It’s a must read for all java developers.

A Perfect book for a desert island!

Posted by admin | Posted in Learning Materials | Posted on 18-08-2007

1

Although not very popular on my university, and actually, I would say the book which puts myself off reading as it’s very difficult I think I have found a perfect book for the desert island. Of course this book must be about programming and must last for many years to read. I’m telling you all guys, I have found one, actually many but like one – “The Art of Computer Programming” by Donald E. Knuth.
Now instead of intellectual chess evening I will probably dive into it as complicated things sometimes fascinate me.

Hey people, if you know any book similar to that one, or at least the one you believe is perfect for the one way trip, you can read it for a very long time and it’s about programming, please let me know. If I will gather enough posts I will create top 10 programming books for the desert island and post it on my blog! Thanks in advance!