当我在“单位”和“价格”列的第一行的单元格中输入值时,列“金额”;列单元格值应设置为单位和数量的乘积。我应该使用哪个听众?请帮忙,因为我是Java的新手。
代码:
JTable jTable1;
DefaultTableModel mod=new DefaultTableModel();
mod.addColumn("No");
mod.addColumn("Item ID");
mod.addColumn("Units");
mod.addColumn("Amount");
mod.addColumn("UOM");
mod.addColumn("Delivery Date");
mod.addColumn("Total Amount");
mod.addColumn("Notes");
mod.addColumn("Received");
mod.addRow(new Object [][] {
{1, null, null, null, null, null, null, null, null}
});
jTable1.setModel(mod);
jTable1.setColumnSelectionAllowed(true);
答案 0 :(得分:4)
我们的想法是实现一个TableModel
,以便它自动返回单位和金额乘积的结果。这是我的意思的小演示(添加一个新行,只需在表格下方双击):
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class TestTable3 {
protected void initUI() {
final DefaultTableModel model = new DefaultTableModel() {
@Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return Integer.class;
case 1:
case 2:
return Double.class;
}
return super.getColumnClass(columnIndex);
}
@Override
public Object getValueAt(int row, int column) {
if (column == 2) {
Integer i = (Integer) getValueAt(row, 0);
Double d = (Double) getValueAt(row, 1);
if (i != null && d != null) {
return i * d;
} else {
return 0.0;
}
}
return super.getValueAt(row, column);
}
@Override
public boolean isCellEditable(int row, int column) {
return column == 0 || column == 1;
}
@Override
public void setValueAt(Object aValue, int row, int column) {
super.setValueAt(aValue, row, column);
fireTableCellUpdated(row, 2);
}
@Override
public String getColumnName(int column) {
switch (column) {
case 0:
return "Quantity";
case 1:
return "Price";
case 2:
return "Total";
}
return super.getColumnName(column);
}
@Override
public int getColumnCount() {
return 3;
}
};
final JTable table = new JTable(model);
table.setFillsViewportHeight(true);
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
if (table.rowAtPoint(e.getPoint()) < 0) {
model.addRow(new Vector());
}
}
}
});
model.addRow(new Vector());
JFrame frame = new JFrame(TestTable3.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollpane = new JScrollPane(table);
frame.add(scrollpane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestTable3().initUI();
}
});
}
}
结果:
答案 1 :(得分:2)
当我在“单位”列的第1行的单元格中输入值时 “价格”,“金额”栏;列单元格值应设置为 单位和数量的乘积