在JTable中加/去行后加减sum的值,可以通过以下步骤实现:
下面是一个示例代码:
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
public class SumJTableExample extends JFrame {
private JTable table;
private JLabel sumLabel;
public SumJTableExample() {
// 创建表格数据
Object[][] data = {
{1, 2},
{3, 4},
{5, 6}
};
// 创建表格列名
String[] columnNames = {"Column 1", "Column 2"};
// 创建TableModel对象
MyTableModel model = new MyTableModel(data, columnNames);
// 创建JTable对象
table = new JTable(model);
// 添加TableModelListener
model.addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
// 更新sum的值
int sum = 0;
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
sum += (int) model.getValueAt(i, j);
}
}
sumLabel.setText("Sum: " + sum);
}
});
// 创建显示sum的标签
sumLabel = new JLabel("Sum: 0");
// 创建布局并添加组件
JPanel panel = new JPanel();
panel.add(new JScrollPane(table));
panel.add(sumLabel);
// 设置窗口属性
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(panel);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SumJTableExample();
}
});
}
// 自定义TableModel
class MyTableModel extends AbstractTableModel {
private Object[][] data;
private String[] columnNames;
public MyTableModel(Object[][] data, String[] columnNames) {
this.data = data;
this.columnNames = columnNames;
}
@Override
public int getRowCount() {
return data.length;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
data[rowIndex][columnIndex] = value;
fireTableCellUpdated(rowIndex, columnIndex);
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
}
}
这个示例代码演示了如何在JTable中加/去行后加减sum的值。每当表格中的单元格值发生变化或行被添加/删除时,都会更新sum的值,并在界面上显示出来。你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云