0

I am try to let a JTable always order, this table is void primary.

I add row by table model. How can I let the new adding row locate the order position?

//the add code
Object[] row= {current_hard_bin_degree,1,String.format("%.2f",1*100.0f/total_bins)+"%"};
DefaultTableModel model = (DefaultTableModel)myTable.getModel();
model.addRow(te);
//i tried to this,but it just can be order when i click the header
 TableRowSorter<TableModel> sorter
                 = new TableRowSorter<TableModel>(myTable.getModel());
         myTable.setRowSorter(sorter);
         sorter.setComparator(0, new Comparator<Object>() {
            public int compare(Object arg0, Object arg1) {
               try {
                  int a = Integer.parseInt(arg0.toString());
                  int b = Integer.parseInt(arg1.toString());
                  return a - b;
               } catch (NumberFormatException e) {
                  return 0;
               }
            }
         });

enter image description here

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
yanglei
  • 1
  • 1
  • For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). Hard code data to replace the table. Note that code which can be compiled and run is better than images of the tables. That's why I did not add the image in the edit. It adds no new information that wasn't already obvious from your description. – Andrew Thompson Sep 24 '20 at 11:36
  • Why are you creating a custom Comparator. Just add a Double object to the TableModel and override the `getColumnClass(...)` method of the model to return Double for that column and the table will use the appropriate comparator. Read the section from the Swing tutorial on [Sorting and Fileter](https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting) for an example. – camickr Sep 24 '20 at 14:35

1 Answers1

0

How about using growx? MigLayout push VS grow

for example,

private void display(int i) {
         model.add(sorter, "cell 0"+i+", growx");
}
Hannah Lee
  • 383
  • 2
  • 7
  • 19