对JTable进行排序,除了最后两行

时间:2014-11-14 11:44:14

标签: java swing sorting user-interface jtable

请查看以下代码。

import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.*;

public class TableBasic extends JFrame
{

    final Class<?>[] columnClasses = new Class<?>[] {Date.class, String.class, Long.class, Boolean.class};



    public TableBasic()
    {

        String[] columnNames = {"Date", "String", "Long", "Boolean"};
        Object[][] data =
        {
            {getJavaDate("13-11-2020"), "A", new Long(1), Boolean.TRUE },
            {getJavaDate("13-11-2018"), "B", new Long(2), Boolean.FALSE},
            {getJavaDate("12-11-2015"), "C", new Long(9), Boolean.TRUE },
            {getJavaDate("12-11-2015"), "D", new Long(4), Boolean.FALSE},
            {null, null, null, null},
            {getJavaDate("12-11-2016"), "N/A", new Long(16), Boolean.FALSE}

        };

        DefaultTableModel model = new DefaultTableModel(data, columnNames) 
        {
            @Override
            public Class<?> getColumnClass(int column) 
            {
                return columnClasses[column];
            }
        };

        JTable table = new JTable();
        table.setModel(model);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        table.setAutoCreateRowSorter(true);
        table.getColumnModel().getColumn(0).setCellRenderer(tableCellRenderer);

        // Sort the rows
        DefaultRowSorter sorter = ((DefaultRowSorter)table.getRowSorter()); 
        ArrayList list = new ArrayList();
        list.add( new RowSorter.SortKey(0, SortOrder.DESCENDING) );
        sorter.setSortKeys(list);
        sorter.sort();

        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
    }

    //Use the Cell Renderer to convert date formats
    private TableCellRenderer tableCellRenderer = new DefaultTableCellRenderer() 
    {

        SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy");

        public Component getTableCellRendererComponent(JTable table,Object value, boolean isSelected, boolean hasFocus,int row, int column) 
        {
            if( value instanceof Date) 
            {
                value = f.format(value);
            }
            return super.getTableCellRendererComponent(table, value, isSelected,hasFocus, row, column);
        }
    };

    //Convert String to java.util.Date
    private Date getJavaDate(String s)
    {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            Date d = sdf.parse(s);
             return d;

        } catch (ParseException ex) {
            Logger.getLogger(TableBasic.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }





    public static void main(String[] args)
    {
        TableBasic frame = new TableBasic();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}

你能看到这张桌子的最后两行吗?它们是夏季行,显示上述行的总和。现在,我需要对这些行进行排序,除了最后两行(在实际应用中,这些数据将从数据库加载)。

当排序发生时,结果就是这样。

enter image description here

如您所见,最后两行也已整理出来。我经历了一些帖子试图找到一种方法来避免排序这最后两行,但我无法做任何有用的事情。

2 个答案:

答案 0 :(得分:4)

评论


真正的解决方案应该是

  • JPanel中的另一个(两个)JTable(由GridBagLayout奠定)用于 JTable,其中JScrollBar永远不会被使用,两个JTable将使用TableColumnModelListener与/同步,在两个JTable中覆盖setValueAt XxxTableModels之间同步值的模型

  • easiest as is possible to do without playing with official bugs,页脚再次使用TableColumnModelListener与/同步,然后JTable是可滚动,过滤,排序等的单独对象,

答案 1 :(得分:2)

您可以尝试引入一个人工隐形列(仅存在于模型中),该列保留摘要行号。因此,简单行具有0值,汇总行具有1(或2,3)值。然后在排序列列表中包含该列。

工作

import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.*;

public class TableBasic extends JFrame
{

    final Class<?>[] columnClasses = new Class<?>[] {Date.class, String.class, Long.class, Boolean.class, Integer.class};



    public TableBasic()
    {

        String[] columnNames = {"Date", "String", "Long", "Boolean", "invisible"};
        Object[][] data =
                {
                        {getJavaDate("13-11-2020"), "A", new Long(1), Boolean.TRUE , 0},
                        {getJavaDate("13-11-2018"), "B", new Long(2), Boolean.FALSE, 0},
                        {getJavaDate("12-11-2015"), "C", new Long(9), Boolean.TRUE , 0},
                        {getJavaDate("12-11-2015"), "D", new Long(4), Boolean.FALSE, 0},
                        {null, null, null, null, 1},
                        {getJavaDate("12-11-2016"), "N/A", new Long(16), Boolean.FALSE, 2}

                };

        DefaultTableModel model = new DefaultTableModel(data, columnNames)
        {
            @Override
            public Class<?> getColumnClass(int column)
            {
                return columnClasses[column];
            }
        };

        JTable table = new JTable();
        table.setModel(model);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        table.setAutoCreateRowSorter(true);
        table.getColumnModel().getColumn(0).setCellRenderer(tableCellRenderer);
        table.removeColumn(table.getColumnModel().getColumn(4));

        // Sort the rows
        DefaultRowSorter sorter = ((DefaultRowSorter)table.getRowSorter());
        ArrayList list = new ArrayList();
        list.add( new RowSorter.SortKey(4, SortOrder.ASCENDING) );
        list.add( new RowSorter.SortKey(0, SortOrder.DESCENDING) );
        sorter.setSortKeys(list);
        sorter.sort();

        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
    }

    //Use the Cell Renderer to convert date formats
    private TableCellRenderer tableCellRenderer = new DefaultTableCellRenderer()
    {

        SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy");

        public Component getTableCellRendererComponent(JTable table,Object value, boolean isSelected, boolean hasFocus,int row, int column)
        {
            if( value instanceof Date)
            {
                value = f.format(value);
            }
            return super.getTableCellRendererComponent(table, value, isSelected,hasFocus, row, column);
        }
    };

    //Convert String to java.util.Date
    private Date getJavaDate(String s)
    {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            Date d = sdf.parse(s);
            return d;

        } catch (ParseException ex) {
            Logger.getLogger(TableBasic.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }





    public static void main(String[] args)
    {
        TableBasic frame = new TableBasic();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}