2012-09-04 77 views
3

我有一個JTable,我希望有時整數(大小列),有時由字符串(文件路徑)排序行。 所以我在谷歌搜索它,我已經到了這裏。我知道我必須重寫DefaultTableModel的方法,稱爲getColumnClass。所以我在這裏鏈接我的代碼。JTable:按整數排序

class Personal_model extends DefaultTableModel{ 

Personal_model(String[][] s,String[] i){ 
     super(s,i); 
} 


@Override 
public Class<?> getColumnClass(int columnIndex){ 

     if (columnIndex!=2) 
       return String.class; 
     else 
       return Integer.class; 

} 
} 

而這裏的代碼來創建表,模型'Personal_model';我也設置了排序器。 但這一切都行不通!!!!!幫我請

 modeltable = new Personal_model(data,col); 
     table = new JTable(modeltable); 
     table.setRowSorter(new TableRowSorter<Personal_model>(modeltable)); 

通常情況下,沒有我的分揀,所有被perfeclty可視化,和字符串排序正確(這是顯而易見的,怎麼一回事,因爲通常這一切都通過串排序。)

+1

請編輯您的問題包括[sscce](http://sscce.org/),顯示你描述的問題。 – trashgod

回答

6

1),請閱讀教程JTable that's contains TableRowSorter example,約RowSorter的問題必須是默認在您的代碼

2)你可以使用如下的定義columnClass的,

public Class getColumnClass(int c) { 
    return getValueAt(0, c).getClass(); 
} 

3),也可以進行硬編碼該

@Override 
    public Class<?> getColumnClass(int colNum) { 
     switch (colNum) { 
      case 0: 
       return Integer.class; 
      case 1: 
       return Double.class; 
      case 2: 
       return Long.class; 
      case 3: 
       return Boolean.class; 
      case 4: 
       return String.class; 
      case 5: 
       return Icon.class; 
      default: 
       return String.class; 
     } 
    } 

4)或覆蓋RowSorter(通知瘋狂的代碼)

enter image description hereenter image description here

import com.sun.java.swing.Painter; 
import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Component; 
import java.awt.Graphics2D; 
import java.util.ArrayList; 
import java.util.List; 
import javax.swing.*; 
import javax.swing.table.*; 

public class JTableSortingIconsForNimbus extends JFrame { 

    private static final long serialVersionUID = 1L; 
    private JTable table; 
    private JTable table1; 
    private static Icon ascendingSortIcon; 
    private static Icon descendingSortIcon; 

    public JTableSortingIconsForNimbus() { 
     Object[] columnNames = {"Type", "Company", "Shares", "Price"}; 
     Object[][] data = { 
      {"Buy", "IBM", new Integer(1000), new Double(80.50)}, 
      {"Sell", "MicroSoft", new Integer(2000), new Double(6.25)}, 
      {"Sell", "Apple", new Integer(3000), new Double(7.35)}, 
      {"Buy", "Nortel", new Integer(4000), new Double(20.00)} 
     }; 
     DefaultTableModel model = new DefaultTableModel(data, columnNames) { 

      private static final long serialVersionUID = 1L; 

      @Override 
      public Class getColumnClass(int column) { 
       return getValueAt(0, column).getClass(); 
      } 
     }; 
     table = new JTable(model) { 

      private static final long serialVersionUID = 1L; 

      @Override 
      public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { 
       Component c = super.prepareRenderer(renderer, row, column); 
       int firstRow = 0; 
       int lastRow = table.getRowCount() - 1; 
       if (row == lastRow) { 
        ((JComponent) c).setBackground(Color.red); 
       } else if (row == firstRow) { 
        ((JComponent) c).setBackground(Color.blue); 
       } else { 
        ((JComponent) c).setBackground(table.getBackground()); 
       } 
       return c; 
      } 
     }; 
     table.setPreferredScrollableViewportSize(table.getPreferredSize()); 
     JScrollPane scrollPane = new JScrollPane(table); 
     add(scrollPane, BorderLayout.NORTH); 
     table1 = new JTable(model) { 

      private static final long serialVersionUID = 1L; 

      @Override 
      public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { 
       Component c = super.prepareRenderer(renderer, row, column); 
       int firstRow = 0; 
       int lastRow = table1.getRowCount() - 1; 
       if (row == lastRow) { 
        ((JComponent) c).setBackground(Color.red); 
       } else if (row == firstRow) { 
        ((JComponent) c).setBackground(Color.blue); 
       } else { 
        ((JComponent) c).setBackground(table1.getBackground()); 
       } 
       return c; 
      } 
     }; 
     table1.setPreferredScrollableViewportSize(table1.getPreferredSize()); 
     JScrollPane scrollPane1 = new JScrollPane(table1); 
     //UIDefaults nimbusOverrides = new UIDefaults(); 
     //nimbusOverrides.put("Table.ascendingSortIcon", ascendingSortIcon); 
     //nimbusOverrides.put("Table.descendingSortIcon", descendingSortIcon); 
     //table1.putClientProperty("Nimbus.Overrides", nimbusOverrides); 
     //UIManager.getLookAndFeelDefaults().put("Table.ascendingSortIcon", ascendingSortIcon); 
     //UIManager.getLookAndFeelDefaults().put("Table.descendingSortIcon", descendingSortIcon); 
     UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].ascendingSortIconPainter", 
       new FillPainter1(new Color(255, 255, 191))); 
     UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].descendingSortIconPainter", 
       new FillPainter1(new Color(191, 255, 255))); 


     SwingUtilities.updateComponentTreeUI(table1); 
     add(scrollPane1, BorderLayout.SOUTH); 
     TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel()) { 

      @Override 
      public void toggleSortOrder(int column) { 
       if (column >= 0 && column < getModelWrapper().getColumnCount() && isSortable(column)) { 
        List<SortKey> keys = new ArrayList<SortKey>(getSortKeys()); 
        if (!keys.isEmpty()) { 
         SortKey sortKey = keys.get(0); 
         if (sortKey.getColumn() == column && sortKey.getSortOrder() == SortOrder.DESCENDING) { 
          setSortKeys(null); 
          return; 
         } 
        } 
       } 
       super.toggleSortOrder(column); 
      } 
     }; 
     table.setRowSorter(sorter); 
     table1.setRowSorter(sorter); 
    } 

    static class FillPainter1 implements Painter<JComponent> { 

     private final Color color; 

     public FillPainter1(Color c) { 
      color = c; 
     } 

     @Override 
     public void paint(Graphics2D g, JComponent object, int width, int height) { 
      g.setColor(color); 
      g.fillRect(0, 0, width - 1, height - 1); 
     } 
    } 

    public static void main(String[] args) { 
     try { 
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); 
      ascendingSortIcon = UIManager.getLookAndFeelDefaults().getIcon("Table.ascendingSortIcon"); 
      descendingSortIcon = UIManager.getLookAndFeelDefaults().getIcon("Table.descendingSortIcon"); 
      UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].ascendingSortIconPainter", 
        new FillPainter1(new Color(127, 255, 191))); 
      UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].descendingSortIconPainter", 
        new FillPainter1(new Color(191, 255, 127))); 
     } catch (Exception fail) { 
     } 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       JTableSortingIconsForNimbus frame = new JTableSortingIconsForNimbus(); 
       frame.setDefaultCloseOperation(EXIT_ON_CLOSE); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 
} 
+0

你可以看到我有一個重寫的方法,名爲getColumnClass – FrancescoN

+2

不得不將'String [] []''改爲'Object [] []',那麼你可以將各種數據類型填充到'TableModel'中,否則所有東西是'String'值,用我的代碼示例測試,並將Object [] []'改爲String [] []'EDIT(必須移除新的Integer和新的Double並將值包裝爲「 1000「) – mKorbel

+0

請仔細看看我的代碼?我有什麼改變? **數據**和** col **都是它們的字符串;你是否告訴我,我必須將** Data **設置爲Object [] []? – FrancescoN

2

麥,如mKorbel如所指出的,你的數據模型由String組成。將數字排序爲String不會按自然順序排序(10會在1之前)。

您需要首先從

Personal_model(String[][] s,String[] i){ 

改變你的模型

Personal_model(Object[][] s,String[] i){ 

然後,您需要確保你在模型中把數據是正確的。我們沒有的代碼段,但不使用StringObject[][]

Object[][] myData = new Object[1][2]; 
myData[0][0] = "This is a String value"; 
myData[0][1] = 1; // This is not a String value 

所有信貸代表號碼mKorbel請

+0

我有一個** data [i + j] [2] =(files [i]的問題。length()/ 1024); ** 其中** File [] [] files **;我已經將類型從** String **更改爲** Object **。但是當我嘗試做那個任務時,錯誤。 **(files [i] .length()/ 1024)**是一個LONG,所以在** getColumnCLass **我改變了**返回Integer.class **到** Long.class **,幫我我不知道 – FrancescoN