使用SQL数据库中的数据代码一个排序表

时间:2017-07-26 14:48:45

标签: database datatable codenameone

我正在开发一个从数据库中检索数据的应用程序。我使用的结构来自这里给出的代码示例:https://www.codenameone.com/javadoc/com/codename1/db/Database.html

我的表格显示数据正常。

现在我想在第一列中对表数据进行排序,其中包含日期作为字符串。

实现这一目标的最佳方法是什么?我尝试过使用JTable的代码,但没有成功......

值得一提的是,这是我的第一个Codename One应用程序,我对Java的体验恢复到不到一年。

2 个答案:

答案 0 :(得分:1)

您可以采取两种方向,第一种方法是更改​​SQL并使用ORDER BY子句来检索正确排序的数据。第二种方法应该适用于任何表:

对于动态可排序表,您将需要更多工作。我调整了JavaDoc中现有的表样本以支持排序。目前我只是为字符串列做了这个,但你可以轻松地替换比较器来做你想要的......

Form hi = new Form("Table", new BorderLayout());
TableModel model = new DefaultTableModel(new String[] {"Col 1", "Col 2", "Col 3"}, new Object[][] {
    {"Row 1", "Row A", "Row X"},
    {"Row 2", "Row B", "Row Y"},
    {"Row 3", "Row C", "Row Z"},
    {"Row 4", "Row D", "Row K"},
    }) {
        public boolean isCellEditable(int row, int col) {
            return col != 0;
        }
    };
Table table = new Table(model) {
    private int currentSortedColum = -1;
    private boolean asc;
    private Button lastSortedColumnButton;

    private void setArrow(int column, Button b) {
        if(column == currentSortedColum) {
            if(asc) {
                FontImage.setMaterialIcon(b, FontImage.MATERIAL_ARROW_UPWARD);
            } else {
                FontImage.setMaterialIcon(b, FontImage.MATERIAL_ARROW_DOWNWARD);                            
            }
        } else {
            FontImage.setMaterialIcon(b, FontImage.MATERIAL_SORT);   
        }
    }

    @Override
    protected Component createCell(Object value, int row, int column, boolean editable) { // (1)
        Component cell;
        if(row == -1) { 
            // table header 
            cell = new Button("" + value, "TableHeader");
            setArrow(column, ((Button)cell));
            ((Button)cell).setTextPosition(LEFT);
            ((Button)cell).addActionListener(e -> {
                if(currentSortedColum != column && lastSortedColumnButton != null) {
                    FontImage.setMaterialIcon(lastSortedColumnButton, FontImage.MATERIAL_SORT);   
                }
                lastSortedColumnButton = (Button)cell;
                if(column == currentSortedColum) {
                    asc = !asc;
                } else {
                    currentSortedColum = column;
                    asc = false;
                }
                setArrow(column, lastSortedColumnButton);
                setModel(new SortedTableModel(currentSortedColum, asc, model, new CaseInsensitiveOrder()));
            });
        } else {
            cell = super.createCell(value, row, column, editable);
        }
        if(row > -1 && row % 2 == 0) { 
            // pinstripe effect 
            cell.getAllStyles().setBgColor(0xeeeeee);
            cell.getAllStyles().setBgTransparency(255);
        }
        return cell;
    }
};
hi.add(BorderLayout.CENTER, table);
hi.show();

为此,您将需要已排序的模型:

class SortedTableModel implements TableModel {
    private TableModel model;
    private int[] sorted;

    public SortedTableModel(int column, boolean asc, TableModel model, Comparator cmp) {
        this.model = model;

        sorted = new int[model.getRowCount()];
        Integer[] sortedTemp = new Integer[sorted.length]; 

        for(int iter = 0 ; iter < sorted.length ; iter++) {
            sortedTemp[iter] = iter;
        }

        // sort(int[]) doesn't accept a comparator how stupid is that...
        Arrays.sort(sortedTemp, (Object o1, Object o2) -> {
                int i1 = (Integer)o1;
                int i2 = (Integer)o2;
                if(asc) {
                    return cmp.compare(model.getValueAt(i1, column), model.getValueAt(i2, column)) * -1;
                }
                return cmp.compare(model.getValueAt(i1, column), model.getValueAt(i2, column));
            }
        );
        for(int iter = 0 ; iter < sorted.length ; iter++) {
            sorted[iter] = sortedTemp[iter];
        }
    }

    @Override
    public int getRowCount() {
        return model.getRowCount();
    }

    @Override
    public int getColumnCount() {
        return model.getColumnCount();
    }

    @Override
    public String getColumnName(int i) {
        return model.getColumnName(i);
    }

    @Override
    public boolean isCellEditable(int row, int column) {
        return model.isCellEditable(sorted[row], column);
    }

    @Override
    public Object getValueAt(int row, int column) {
        return model.getValueAt(sorted[row], column);
    }

    @Override
    public void setValueAt(int row, int column, Object o) {
        model.setValueAt(sorted[row], column, o);
    }

    @Override
    public void addDataChangeListener(DataChangedListener d) {
        model.addDataChangeListener(d);
    }

    @Override
    public void removeDataChangeListener(DataChangedListener d) {
        model.removeDataChangeListener(d);
    }
}

它产生了这个:

Dynamic table sorting

答案 1 :(得分:0)

总结所有有价值的信息,我得到了以下解决方案,我发现它更直接:

  1. 从DatePicker获取日期为Long值并添加到数据库:

    Long long_Date = gui_date_Picker.getDate().getTime();
    
  2. 从数据库中检索字符串数字,将其转换为long,转换为日期并放入表中:

    DefaultTableModel model = new DefaultTableModel(new String[]{"Date", "Termin"}, new Object[][] {{}} );
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    
    Database db = null;
    Cursor cur = null;
    
    db = Display.getInstance().openOrCreate("MyDB2.db");
    db.execute("CREATE TABLE IF NOT EXISTS Termine (Date NOT NULL,Event NOT NULL)");
    cur = db.executeQuery("select * from Termine ORDER BY Date ASC; ");
    
    while (cur.next()) {
    
        Row currentRow = cur.getRow();
        String date = currentRow.getString(0);
        String termin = currentRow.getString(1);
    
        Long l = Long.parseLong(date, 10);
        Date date_from_String = new Date(l);
    
        String string_from_Date = formatter.format(date_from_String);
        System.out.println(string_from_Date);
    
    
        model.addRow(new Object[]{string_from_Date, termin });
    }
    
    
    Table table = new Table(model);