我正在開發一個需要使用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:
}
}
}
只是強調,已經在別處提到:你**絕不能**在編輯器中的數據的行爲,這不是它的工作。它的** only *工作是在編輯終止時採取輸入並通知其監聽者,沒有別的。 – kleopatra
順便說一句:請學習java命名約定並堅持下去。 – kleopatra