那不是JTABLE的本身的事情,你可以在生成JTABLE显示数据时候添加一列,然后把序号放
进去就好了

解决方案 »

  1.   

    从oralce数据库选择表,在Jtable中显示,能排序。
    /**
       @version 1.00 2001-07-18
       @author ouyang
    */import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.net.*;
    import java.sql.*;
    import java.io.*;/**
       This program demonstrates how to sort a table column.
       Double-click on a table columm to sort it.
    */
    public class BAK_TableSortTest
    {  
       public static void main(String[] args)
       {  
          JFrame frame = new TableSortFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.show();
       }
    }/**
       This frame contains a table of planet data.
    */
    class TableSortFrame extends JFrame
    {  
    public TableSortFrame()
    {  
    setTitle("TableSortTest");
    setSize(WIDTH, HEIGHT);       // setup JComboBox and JScrollPane
           Container contentPane = getContentPane();
           tableNames = new JComboBox();
           tableNames.addActionListener(new
              ActionListener()
              {
                 public void actionPerformed(ActionEvent event)
                 {
                    showTable((String)tableNames.getSelectedItem());
                 }
              });
          contentPane.add(tableNames, BorderLayout.NORTH);
          scrollPane = new JScrollPane(new JPanel());
          contentPane.add(scrollPane, BorderLayout.CENTER);
          
          // and Listener  when window closing
           addWindowListener(new
              WindowAdapter()
              {  
                 public void windowClosing(WindowEvent e)
                 {  
                   try
                   {  
                      if(stat!=null)
                       stat.close();
                      if(conn!=null)
                       conn.close();
                   }
                   catch(SQLException ex) 
                   {
                      while (ex != null)
                      {
                         ex.printStackTrace();
                         ex = ex.getNextException();
                      }
                   }
                 }
             });
            
          try
          {  
             conn = getConnection();         
             stat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
             //stat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
             getTableNames();
          }  
          catch(Exception ex)
          {           
             ex.printStackTrace();
             //JOptionPane.showMessageDialog(this, ex);
          }  
        }
       
        public static Connection getConnection()
          throws SQLException, IOException
       {  
          Properties props = new Properties();
          FileInputStream in 
             = new FileInputStream("database.properties");
          props.load(in);
          in.close();      String drivers = props.getProperty("jdbc.drivers");
          if (drivers != null)
             System.setProperty("jdbc.drivers", drivers);
          String url = props.getProperty("jdbc.url");      
          String username = props.getProperty("jdbc.username");
          String password = props.getProperty("jdbc.password");
          
          return
             DriverManager.getConnection(url, username, password);
       }
       
       public void getTableNames() throws SQLException
       {
          Statement tmpstat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
                ResultSet  tmprs = tmpstat.executeQuery("SELECT TABLE_NAME TABLE_NAME FROM USER_TABLES UNION  SELECT VIEW_NAME TABLE_NAME FROM USER_VIEWS");     
          while (tmprs.next())
                  tableNames.addItem(tmprs.getString(1));
                tmprs.close();
                tmpstat.close();
                
         /*
          ResultSet mrs = meta.getTables(null, null, null,
             new String[] { "TABLE" });
          
          System.out.println("meta.getTables success: "+meta);
          while (mrs.next())
              tableNames.addItem(mrs.getString(3));
          mrs.close();
          */
       }
       
        public void getFieldNameAndValues()
        {
        try{
        ResultSetMetaData rsmd = rs.getMetaData();
        columnNames =new String[rsmd.getColumnCount()];
        int columnCount=rsmd.getColumnCount();
       
          //set columnNames FileName
          for (int i = 1; i <= columnCount; i++)
          {  
             columnNames[i-1] = rsmd.getColumnLabel(i);
          }
          
          // set ceil values
          rs.last();
          int b=rs.getRow();
          rs.first();
          int a =rs.getRow();
           int c =(b-a+1);
          
           cells =new Object[c][columnCount];
           rs.beforeFirst();
           int count=0;
          while (rs.next())
          {  
             for (int i = 1; i <= columnCount; i++)
             { 
                cells[count][i-1]=rs.getObject(i);
             }
             count++;
    }
    }catch(SQLException e )
       {
       System.out.println("getFieldNameAndValues error :"+e);
       //JOptionPane.showMessageDialog(this, e) ;
       }
    }

       public void showTable(String tableName)
       {  
          if(tableName==null)
           return;
          try
          {          
            
             if (rs != null) rs.close();
             rs = stat.executeQuery("SELECT * FROM " + tableName);                
             getFieldNameAndValues();
             model      = new DefaultTableModel(cells, columnNames);
             sorter = new SortFilterModel(model);
             table = new JTable(sorter);
             table.setSelectionBackground(Color.blue);
             table.getTableHeader().addMouseListener(new 
             MouseAdapter()
             {  
                public void mouseClicked(MouseEvent event)
                {  
                   // check for double click
                   if (event.getClickCount() < 2) return;               // find column of click and
                   int tableColumn
                      = table.columnAtPoint(event.getPoint());               // translate to table model index and sort
                   int modelColumn
                      = table.convertColumnIndexToModel(tableColumn);
                   sorter.sort(modelColumn);
                }
             });
             if (scrollPane != null) 
                getContentPane().remove(scrollPane); 
             scrollPane = new JScrollPane(table);
             getContentPane().add(scrollPane, BorderLayout.CENTER);
             validate();   
          }
          catch(SQLException e)
          {  
             System.out.println("showTable error :"+e);
       //JOptionPane.showMessageDialog(this, e) ;
          }
       }
       
       private Object[][] cells ;
       private String[] columnNames ;
       
       private static final int WIDTH = 400;
       private static final int HEIGHT = 200;
       private static JComboBox tableNames ;
       private static   Component scrollPane;
       private static   DefaultTableModel model;
       private static   SortFilterModel sorter ;
       private static   JTable table;
       
       private Connection conn;
       private Statement stat;
       private DatabaseMetaData meta;
       private ResultSet rs;
       
    }
      

  2.   


    /**
       This table model takes an existing table model and produces
       a new model that sorts the rows so that the entries in
       a particular column are sorted.
    */
    class SortFilterModel extends AbstractTableModel
    {
       /**
          Constructs a sort filter model.
          @param m the table model to filter
       */
       public SortFilterModel(TableModel m)
       {  
          model = m;
          rows = new Row[model.getRowCount()];
          for (int i = 0; i < rows.length; i++)
          {  
             rows[i] = new Row();
             rows[i].index = i;
          }
       }   /**
          Sorts the rows.
          @param c the column that should become sorted
       */
       public void sort(int c)
       {  
          sortColumn = c;
          Arrays.sort(rows);
          fireTableDataChanged();
       }   // Compute the moved row for the three methods that access
       // model elements   public Object getValueAt(int r, int c)
       {  
          return model.getValueAt(rows[r].index, c);
       }   public boolean isCellEditable(int r, int c)
       {  
          return model.isCellEditable(rows[r].index, c);
       }   public void setValueAt(Object aValue, int r, int c)
       {  
          model.setValueAt(aValue, rows[r].index, c);
       }   // delegate all remaining methods to the model   public int getRowCount()
       {  
          return model.getRowCount();
       }   public int getColumnCount()
       {  
          return model.getColumnCount();
       }   public String getColumnName(int c)
       {  
          return model.getColumnName(c);
       }   public Class getColumnClass(int c)
       {  
          return model.getColumnClass(c);
       }   /** 
          This inner class holds the index of the model row
          Rows are compared by looking at the model row entries
          in the sort column.
       */
       private class Row implements Comparable
       {  
          public int index;
          public int compareTo(Object other)
          {         
             Row otherRow = (Row)other;
             Object a = model.getValueAt(index, sortColumn);
             Object b = model.getValueAt(otherRow.index, sortColumn);       
             if(a==null)
              return -1;
             if(b==null)
              return 1;
             if (a instanceof Comparable)
                return ((Comparable)a).compareTo(b);
             else
                return a.toString().compareTo(b.toString());
          }
       }   private TableModel model;
       private int sortColumn;
       private Row[] rows;
    }