Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting arrows jtable column header

Does anyone know how to implement the up and down arrows of a JTable column header while sorting its rows?

I have made my own way of sorting and it is triggered by listening to mouse clicks by mouseadapter and the only things that is left is the visibility of such arrows on the header...

Is there also a way to easily implement a sortable jtable?


I finished doing all the sorting and one last thing that i can't do is show the sorting arrows..

i don't want to make a new one but i failed to find if there is an setEnableArrow or something..

any ideas about this?

like image 761
ironmaurus Avatar asked Oct 12 '11 19:10

ironmaurus


2 Answers

You can take a look in the source code of the DefaultTableCellHeaderRenderer. In the getTableCellRendererComponent you see from where those icons are retrieved (e.g. UIManager.getIcon("Table.ascendingSortIcon")) and how this icon is set (setIcon(sortIcon);)

like image 140
Robin Avatar answered Oct 18 '22 06:10

Robin


I suggest you don't mess up with the DefaultTableCellHeaderRenderer. The problem with this one, is that it's just that, the default. Each LaF is supposed to create a subclass of this one and do its own rendering there. My suggestion is to use a LaF that provides this functionality out of the box. I think that TinyLaf can do this but I'm not sure. You can subclass DefaultTableCellHeaderRenderer but you risk alienating the header rendering from the rest of the LaF.

So how to do it? Unicode to the rescue! Refer to the geometric shapes page and use what you like. I picked the '\u25B2' and '\u25BC' triangles. But then I had to hide the dreaded Swing icon:

UIManager.put( "Table.ascendingSortIcon", new EmptyIcon() );
UIManager.put( "Table.descendingSortIcon", new EmptyIcon() );

Be very careful with the above lines! They will replace the icons for all JTables in your application which might not be what you want. Then you should be able to see something like that:

Sorting icon unicode

Empty Icon can be like:

class EmptyIcon implements Icon, Serializable {
    int width = 0;
    int height = 0;
    public void paintIcon(Component c, Graphics g, int x, int y) {}
    public int getIconWidth() { return width; }
    public int getIconHeight() { return height; }
}
like image 24
Stelios Adamantidis Avatar answered Oct 18 '22 07:10

Stelios Adamantidis