开发者

sorting arrows jtable column header

开发者 https://www.devze.com 2023-04-12 09:29 出处:网络
Does anyone know how to implement the up and down arrows of a JTable column header while sorting its rows?

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 trigge开发者_运维百科red 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?


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);)


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 arrows jtable column header

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; }
}


This is the easiest way to implement sorting:

    MyModel model = new MyModel();
    TableRowSorter<MyModel> sorter = new TableRowSorter<MyModel> (model);
    jTable1 = new javax.swing.JTable();
    jTable1.setRowSorter(sorter);
    jTable1.setModel(model);


What if you use JXtable instead of a Jtable?

these tables have the arrows in the header to sort them and they are easy to use... worth trying...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号