Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.Arrays;
import java.util.Comparator;
import java.util.Vector;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class Main {
    public static void main(String[] argv) throws Exception {
        DefaultTableModel model = new DefaultTableModel();
        JTable table = new JTable(model);
        table.setAutoCreateColumnsFromModel(false);

        boolean ascending = false;
        Vector data = model.getDataVector();
        Object[] colData = new Object[model.getRowCount()];

        for (int i = 0; i < colData.length; i++) {
            colData[i] = ((Vector) data.get(i)).get(0);
        }
        Arrays.sort(colData, new ColumnSorter());
        for (int i = 0; i < colData.length; i++) {
            ((Vector) data.get(i)).set(0, colData[i]);
        }
        model.fireTableStructureChanged();
    }
}

class ColumnSorter implements Comparator {
    ColumnSorter() {
    }

    public int compare(Object a, Object b) {
        if (a instanceof String && ((String) a).length() == 0) {
            a = null;
        }
        if (b instanceof String && ((String) b).length() == 0) {
            b = null;
        }
        if (a == null && b == null) {
            return 0;
        } else if (a == null) {
            return 1;
        } else if (b == null) {
            return -1;
        } else if (a instanceof Comparable) {
            return ((Comparable) a).compareTo(b);
        } else {
            return a.toString().compareTo(b.toString());
        }
    }
}