Setting the sort order between 2 rows in MySQL can be done in 1 line by making use of the IF() function.

I had a scenario where I had move up and move down functionalities to set the order of my database entries.

Let us say, you have columns ID and SORT_ORDER.

This line of code should do the trick.

JTable has an auto sorting feature through the use of the setAutoCreateRowSorter() method. However, try inserting a new row to its DefaultTableModel and you will find out it is not displayed correctly at the right index row position if the JTable is in sort mode.

There is no automatic way to fix this problem with just a set method. You will have to instantiate a TableRowSorter object and assign that DefaultTableModel as its parameter, assign it to the JTable‘s setRowSorter() method and set the TableRowSorter‘s setSortsOnUpdates() method to true.

See sample code below.

That should fix it. So whenever you insert a new row and you already clicked a column header to sort the JTable in ascending or descending order, the newly added row will be sorted accordingly right away.

Recently I wrote a post on how to sort JTree nodes alphabetically. But what if you want certain nodes that are equal to some words and you want them to always stay as the first and last node.

For example, I want to make the String “CARS” to always be the first node in the JTree and the String “HOUSE” to be the last while the rest of the tree nodes will be sorted alphabetically.

Using the value of the compare() method of the Comparator class, I did a dirty workaround to make this work with a little help from the Math class.

Related Posts Plugin for WordPress, Blogger...