Java自动计算表格某一数字列的和
[java]
package com.han;
import java.awt.BorderLayout;
import java.awt.Container;
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;
/**
* 自动计算表格某一数字列的和
* @author HAN
*
*/
public class TabelModelEvent_2 extends JFrame {
/**
*
*/
private static final long serialVersionUID = 7045416728019138021L;
float sum = 0;
public TabelModelEvent_2() {
// 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);
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);
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();
// keep that every cell value is float or null.
try {
Float.parseFloat((String) defaultTabelModel.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
}
for (int i = 0; i < 4; i++) {
Object cellValue = defaultTabelModel.getValueAt(i, 0);
if (cellValue != null) {
float floatValue = Float
.parseFloat((String) cellValue);
sum += floatValue;
}
}
补充:软件开发 , Java ,