2013-07-19 131 views
0

我正在開發一個需要使用jtable接受數據庫輸入的項目。爲jtable單元格設置事件

我想爲jtable中的單元格設置事件列表程序,關於什麼事件用於我知道的任何建議當用戶完成編輯單元格以便我可以保存單元格的內容並允許用戶移動到下一個單元格,

我有這樣的代碼,但它不工作,我想請你幫我看看,並告訴我我在哪裏犯錯

DefaultTableModel tablemodel; 

/** 
* Creates new form Tabletest 
*/ 
public Tabletest(java.awt.Frame parent, boolean modal) { 
    super(parent, modal); 
    initComponents(); 
    SetTable(); 
} 

/** 
* 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() { 

    jScrollPane1 = new javax.swing.JScrollPane(); 
    jTable1 = new javax.swing.JTable(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); 

    jTable1.setModel(new javax.swing.table.DefaultTableModel(
     new Object [][] { 
      {null, null, null, null}, 
      {null, null, null, null}, 
      {null, null, null, null}, 
      {null, null, null, null} 
     }, 
     new String [] { 
      "Title 1", "Title 2", "Title 3", "Title 4" 
     } 
    )); 
    jTable1.addMouseListener(new java.awt.event.MouseAdapter() { 
     public void mouseClicked(java.awt.event.MouseEvent evt) { 
      jTable1MouseClicked(evt); 
     } 
    }); 
    jTable1.addKeyListener(new java.awt.event.KeyAdapter() { 
     public void keyPressed(java.awt.event.KeyEvent evt) { 
      jTable1KeyPressed(evt); 
     } 
    }); 
    jScrollPane1.setViewportView(jTable1); 

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
    getContentPane().setLayout(layout); 
    layout.setHorizontalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(layout.createSequentialGroup() 
      .addGap(38, 38, 38) 
      .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addContainerGap(72, Short.MAX_VALUE)) 
    ); 

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

private void jTable1KeyPressed(java.awt.event.KeyEvent evt) { 
    // TODO add your handling code here: 
} 

private void jTable1MouseClicked(java.awt.event.MouseEvent evt) { 
    jTable1.getColumn(jTable1.getColumnName(jTable1.getSelectedColumn())).setCellEditor(new tablecell2()); // TODO add your handling code here: 
} 

/** 
* @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(Tabletest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(Tabletest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(Tabletest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(Tabletest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 
    //</editor-fold> 

    /* Create and display the dialog */ 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      Tabletest dialog = new Tabletest(new javax.swing.JFrame(), true); 
      dialog.addWindowListener(new java.awt.event.WindowAdapter() { 
       @Override 
       public void windowClosing(java.awt.event.WindowEvent e) { 
        System.exit(0); 
       } 
      }); 
      dialog.setVisible(true); 
     } 
    }); 
} 
// Variables declaration - do not modify 
private javax.swing.JScrollPane jScrollPane1; 
private javax.swing.JTable jTable1; 
// End of variables declaration 

void SetTable(){ 
    try { 
     tablemodel= new DefaultTableModel(); 
     tablemodel.addColumn("field1"); 
     tablemodel.addColumn("field2"); 
     tablemodel.addColumn("field3"); 
     tablemodel.addColumn("field4"); 

     Object[] a = {"10","20","30","40"}; 
     Object[] b = {"100","200","300","400"}; 
     tablemodel.addRow(a); 
     tablemodel.addRow(b); 
     jTable1.setModel(tablemodel); 
    } catch (Exception e) { 
    } 
} 

void saveresult() { 
    double tot = Double.parseDouble(jTable1.getValueAt(jTable1.getSelectedRow(), jTable1.getSelectedColumn()).toString()); 
    JOptionPane.showMessageDialog(rootPane, tot+ " the value will be save into db"); 

} 

class tablecell2 extends JTextField implements TableCellEditor { 

    int tablecell2_column; 
    Object value; 

    @Override 
    public Component getTableCellEditorComponent(JTable table, final Object value, boolean isSelected, int row, int column) { 
     this.stopCellEditing(); 
     this.tablecell2_column = column; 
     this.value = value; 
     //this.setFont(null); 
     System.out.println(">>tablecell2>>"); 
     if (value != null) { 
      setText(value.toString()); 
     } 

     this.addFocusListener(new java.awt.event.FocusAdapter() { 
      public void focusLost(java.awt.event.FocusEvent evt) { 
       jTextField1FocusLost(evt); 
      } 

      private void jTextField1FocusLost(FocusEvent evt) { 
       //setText(value.toString()); 
       // new setResults().getbyclass(jTable1, ClassCombo.getSelectedItem().toString(), acadYr, term, subjectCombo.getSelectedItem().toString()); 
       //JOptionPane.showMessageDialog(currentCell, "focus"); 
      } 
     }); 

     this.setPreferredSize(new java.awt.Dimension(15, 20)); 
     this.setFont(new java.awt.Font("", 10, 9)); 
     //this.setFont(new java.awt.Font); 
     /* this.addFocusListener(null);addFocusListener(new java.awt.event.FocusAdapter() { 
     @Override 
     public void focusLost(java.awt.event.FocusEvent evt) { 
     jTable1FocusLost(evt); 
     } 
     });*/ 
     this.addMouseListener(new java.awt.event.MouseAdapter() { 
      public void mouseClicked(java.awt.event.MouseEvent evt) { 
       jTextFieldMouseClicked(evt); 
      } 

      private void jTextFieldMouseClicked(MouseEvent evt) { 
       setText(""); 
      } 
     }); 
     this.addKeyListener(new java.awt.event.KeyAdapter() { 
      @Override 
      public void keyPressed(java.awt.event.KeyEvent evt) { 
       jTextField10KeyPressed(evt); 
      } 
     }); 
     return this; 
    } 

    @Override 
    public Object getCellEditorValue() { 
     throw new UnsupportedOperationException("Not supported yet."); 
    } 

    @Override 
    public boolean isCellEditable(EventObject anEvent) { 
     return true; 
    } 

    @Override 
    public boolean shouldSelectCell(EventObject anEvent) { 
     return true; 
    } 

    @Override 
    public boolean stopCellEditing() { 
     return true; 
    } 

    @Override 
    public void cancelCellEditing() { 
    } 

    @Override 
    public void addCellEditorListener(CellEditorListener l) { 
    } 

    @Override 
    public void removeCellEditorListener(CellEditorListener l) { 
    } 

    private void jTable1FocusLost(java.awt.event.FocusEvent evt) { 
     JOptionPane.showMessageDialog(this, "666"); 

    } 

    private void jTextField10KeyPressed(java.awt.event.KeyEvent evt) { 
     int keycode = evt.getKeyCode(); 
     StringBuffer sb = new StringBuffer(); 
     sb.append("" + evt.getKeyChar()); 
     //jTextField10.setText(sb.toString()); 
     System.out.println("key code " + keycode); 
     if (keycode == 10) { 

      setText(this.getText()); 
      if (tablecell2_column == 3) { 
       //Scores.CA_SCORE = Double.parseDouble(this.getText()); 
      } else if (tablecell2_column == 4) { 
       //Scores.EXAM_SCORE = Double.parseDouble(this.getText()); 
      } 
      //jTextField10.setText(""); 
      sb.delete(0, sb.length()); 
      //JOptionPane.showMessageDialog(currentCell, Scores.CA_SCORE); 
      saveresult(); 
      this.nextFocus(); 
      //new setResults().getbyclass(jTable1, ClassCombo.getSelectedItem().toString(), acadYr, term, subjectCombo.getSelectedItem().toString()); 

     }  // TODO add your handling code here: 
    } 
} 

}

+0

只是強調,已經在別處提到:你**絕不能**在編輯器中的數據的行爲,這不是它的工作。它的** only *工作是在編輯終止時採取輸入並通知其監聽者,沒有別的。 – kleopatra

+0

順便說一句:請學習java命名約定並堅持下去。 – kleopatra

回答

1

從JDK API您可以添加一個TableModelListenerTableModel。您可能需要考慮Table Cell Listener

+0

設置你自己的單元格編輯器類是一個壞主意,例如'jtextfield'並在此組件中驗證? – nachokk

2

當編輯過程自動完成時,將通過setValueAt方法調用表格模型。您的表格模型應該重寫此方法並適當地存儲編輯過程的結果。

TableModel#setValueAtHow to use tables更多細節

+0

使用'CellEditorListener'是一個好主意? – nachokk

+1

@nachokk我不這麼認爲。編輯返回值是編輯的責任。表格模型的職責是存儲該值。 JTable已經充當了這兩者之間的中介,所以有什麼意義呢? – MadProgrammer

+0

只是在飛,混合關於我對camickr的問題,因爲我不喜歡驗證setValueAt我想如果存在另一種方式,如製作自己的編輯器和驗證那裏(與CellEditorListener無關) – nachokk

0

感謝所有我tableModelListener解決了這個問題,這裏是代碼

進口java.awt.event.KeyEvent中;

import javax.swing。*;

import javax.swing.event。*;

import javax.swing.table。*;

公共類TableProcessing擴展的JFrame {

private static final long serialVersionUID = 1L; 
public JTable table = new javax.swing.JTable(); 
private String[] columnNames = {"Item", "Quantity", "Price", "Cost"}; 
private Object[][] data = { 
    {"Bread", new Integer(1), new Double(1.11), new Double(1.11)}, 
    {"Milk", new Integer(1), new Double(2.22), new Double(2.22)}, 
    {"Tea", new Integer(1), new Double(3.33), new Double(3.33)}, 
    {"Cofee", new Integer(1), new Double(4.44), new Double(4.44)}}; 
private TableModelListener tableModelListener; 

public TableProcessing() { 

    DefaultTableModel model = new DefaultTableModel(data, columnNames); 
    table = new JTable(model) { 

     private static final long serialVersionUID = 1L; 

     @Override// Returning the Class of each column will allow different renderers 
     public Class getColumnClass(int column) { // to be used based on Class 
      return getValueAt(0, column).getClass(); 
     } 

     @Override // The Cost is not editable 
     public boolean isCellEditable(int row, int column) { 
      int modelColumn = convertColumnIndexToModel(column); 
      return (modelColumn == 3) ? false : true; 
     } 
    }; 
    table.setPreferredScrollableViewportSize(table.getPreferredSize()); 
    //http://stackoverflow.com/questions/7188179/jtable-focus-query/7193023#7193023 
    table.setCellSelectionEnabled(true); 
    KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0); 
    InputMap map = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 
    map.put(tab, "selectNextRowCell"); 
    //http://stackoverflow.com/questions/7188179/jtable-focus-query/7193023#7193023 
    JScrollPane scrollPane = new JScrollPane(table); 
    getContentPane().add(scrollPane); 
    setTableModelListener(); 
} 

private void setTableModelListener() { 
    System.out.println("enter listen"); 
    tableModelListener = new TableModelListener() { 

     @Override 
     public void tableChanged(TableModelEvent e) { 
      if (e.getType() == TableModelEvent.UPDATE) { 
       System.out.println("Cell " + e.getFirstRow() + ", " 
         + e.getColumn() + " changed. The new value: " 
         + table.getModel().getValueAt(e.getFirstRow(), 
         e.getColumn())); 
       int row = e.getFirstRow(); 
       int column = e.getColumn(); 
       if (column == 1 || column == 2) { 
        TableModel model = table.getModel(); 
        int quantity = ((Integer) model.getValueAt(row, 1)).intValue(); 
        double price = ((Double) model.getValueAt(row, 2)).doubleValue(); 
        Double value = new Double(quantity * price); 
        model.setValueAt(value, row, 3); 
       } 
      } 
     } 
    }; 
    table.getModel().addTableModelListener(tableModelListener); 
} 



public static void main(String[] args) { 
    SwingUtilities.invokeLater(new Runnable() { 

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

}

+0

很高興你解決了你的問題:-)只是:不要推翻它的模型決定,以擴大模型的限制 – kleopatra