2013-12-10 4 views
0

Как узнать, был ли столбец отменен с моим подклассом TableModel. Я хочу, чтобы сделать одну из столбца таблицы, чтобы быть Date типа данных и разбирайтесь по убыванию, но я не уверен, о типе данных столбца, так как, когда я распечатать их все они дают выход:JXTable date column

class org.jdesktop.swingx.table.TableColumnExt

Это мой код:

public class NewJFrame extends javax.swing.JFrame { 

    /** 
    * Creates new form NewJFrame 
    */ 
    public NewJFrame() { 
     initComponents(); 
     for (int i = 0; i < jtbSchedule.getColumnCount(true); i++) { 
      System.out.println("column " + i + ": " + jtbSchedule.getColumn(i).getClass()); 
     } 
    } 

    /** 
    * This method is called from within the constructor to initialize the form. 
    * WARNING: Do NOT modify this code. The content of this method is always 
    * regenerated by the Form Editor. 
    */ 
    @SuppressWarnings("unchecked") 
    // <editor-fold defaultstate="collapsed" desc="Generated Code">       
    private void initComponents() { 

     jScrollPane2 = new javax.swing.JScrollPane(); 
     jtbSchedule = new org.jdesktop.swingx.JXTable(new MyTableModel()); 

     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

     jtbSchedule.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] { 
       {null, null, null, null} 
      }, 
      new String [] { 
       "Title 1", "Title 2", "Title 3", "Title 4" 
      } 
     )); 
     jScrollPane2.setViewportView(jtbSchedule); 

     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(layout.createSequentialGroup() 
       .addContainerGap() 
       .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addContainerGap(118, Short.MAX_VALUE)) 
     ); 
     layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(layout.createSequentialGroup() 
       .addContainerGap() 
       .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) 
     ); 

     pack(); 
    }// </editor-fold>       

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String args[]) { 
     /* Set the Nimbus look and feel */ 
     //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
     /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */ 
     try { 
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
       if ("Nimbus".equals(info.getName())) { 
        javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
        break; 
       } 
      } 
     } catch (ClassNotFoundException ex) { 
      java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } 
     //</editor-fold> 

     /* Create and display the form */ 
     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       new NewJFrame().setVisible(true); 
      } 
     }); 
    } 
    // Variables declaration - do not modify      
    private javax.swing.JScrollPane jScrollPane2; 
    private org.jdesktop.swingx.JXTable jtbSchedule; 
    // End of variables declaration     

    public class MyTableModel extends DefaultTableModel { 

     @Override 
     public Class getColumnClass(int col) { 
      if (col == 3) { 
       return java.util.Date.class; 
      } else { 
       return super.getColumnClass(col); // return the appropriate class for every column 
      } 
     } 
    } 
} 

ответ

2

О табличных моделях:

  • Первый раз, когда вы initizialize таблицы с MyTableModel экземпляров.
  • Две строки после того, как вы переопределили модель, установив новый экземпляр DefaultTableModel.

Посмотрите комментарии ниже:

jtbSchedule = new org.jdesktop.swingx.JXTable(new MyTableModel());// Here you set a MyTableModel instance 
    ... 
    jtbSchedule.setModel(new javax.swing.table.DefaultTableModel(
     new Object [][] { 
      {null, null, null, null} 
     }, 
     new String [] { 
      "Title 1", "Title 2", "Title 3", "Title 4" 
     } 
    )); // But here you override the table model setting a DefaultTableModel instance 

В любом случае этот метод:

System.out.println("column " + i + ": " + jtbSchedule.getColumn(i).getClass()); 

Это напечатает класс TableColumn возвращаемый JTable.getColumn() способом, а не столбец класс таблицы. Это должно быть:

for(int i = 0; i < jtbSchedule.getModel().getColumnCount(); i++){ 
    System.out.println("column " + i + ": " + jtbSchedule.getModel().getColumnClass(i)); 
} 
+0

Я использую netbeans, и эти коды генерируются автоматически. Есть ли способ, которым я могу это решить? –

+1

У вас есть два варианта: 1) Установите экземпляр 'MyTableModel' в конструкторе сразу после' initComponents() 'метода. 2) Избавьтесь от разработчиков GUI и сделайте GUI вручную. Код будет более простым и чистым, и вы узнаете много материала о Swing, который скрывает вас GUI-строитель :) @YOLO – dic19

+0

как я могу установить модель, я вставляю весь блок 'jtbSchedule.setModel (новый MyTableModel (... '. Есть ли еще один шаг, который нужно выполнить заранее, я хочу научиться создавать свою собственную модель с моим собственным типом данных date –