Java自动计算表格某一数字列的和(2)
[java]
package com.han;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
/**
* 自动计算表格某一数字列的和(2)
* @author HAN
*
*/
public class TableModelEvent_2_Modified extends JFrame {
/**
*
*/
private static final long serialVersionUID = 465495126108026319L;
float sum = 0;
Object currentSelectedValue;
public TableModelEvent_2_Modified() {
// TODO Auto-generated constructor stub
final Container container = getContentPane();
JScrollPane scrollPane = new JScrollPane();
Vector<String> tableNames = new Vector<String>();
tableNames.add("数字列");
Vector<Vector<String>> tableValues = new Vector<Vector<String>>();
for (int i = 0; i < 4; i++) {
Vector<String> vector = new Vector<String>();
vector.add(null);
tableValues.add(vector);
}
final DefaultTableModel defaultTabelModel = new DefaultTableModel(
tableValues, tableNames);
final JTable table = new JTable(defaultTabelModel);
scrollPane.setViewportView(table);
container.add(scrollPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
JLabel label = new JLabel("数字列总和:");
final JTextField textField = new JTextField(10);
panel.add(label);
panel.add(textField);
container.add(panel, BorderLayout.SOUTH);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
currentSelectedValue = table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
}
}
});
defaultTabelModel.addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
// TODO Auto-generated method stub
if (e.getType() == TableModelEvent.UPDATE) {
int row = e.getFirstRow();
int column = e.getColumn();
if (currentSelectedValue != null) {
sum -= Float.parseFloat((String) currentSelectedValue);
}
// keep that every cell value is float or null.
try {
sum += Float.parseFloat((String) table.getValueAt(row, column));
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(container,
"Your input object is not a float type");
defaultTabelModel.setValueAt(null, row, column);
} catch (NullPointerException e2) {
// do nothing
}
 
补充:软件开发 , Java ,