为jtable单元格设置事件

时间:2013-07-19 01:47:41

标签: java swing 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:
    }
}

}

3 个答案:

答案 0 :(得分:2)

当编辑过程自动完成时,将通过setValueAt方法调用表模型。您的表模型应该覆盖此方法并适当地存储编辑过程的结果。

有关详细信息,请参阅TableModel#setValueAtHow to use tables

答案 1 :(得分:1)

您可以在JDK API中向TableModelListener添加TableModel

或者您可能需要考虑Table Cell Listener

答案 2 :(得分:0)

谢谢所有我用tableModelListener解决了它,这是代码

import java.awt.event.KeyEvent;

导入javax.swing。*;

导入javax.swing.event。*;

导入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);
        }
    });
}

}