import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
class MyTableModel extends AbstractTableModel {
private static final long
serialVersionUID = 1L;
private String[] columnNames = {
"Input 1",
"Input 2",
"Sum",
"Product",
"Difference",
"Quotient"};
private Double[][] data = {
{10.0,
2.0, 12.0, 20.0, 8.0, 5.0},
{100.0,
20.0, 120.0, 2000.0, 80.0, 5.0},
{1.0,
1.0, 2.0, 1.0, 0.0, 1.0},
{25.0,
5.0, 30.0, 5.0, 20.0, 5.0}
};
public String[] getColumnNames() {
return columnNames; }
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public Class getColumnClass(int c) {
return getValueAt(0,
c).getClass();
}
public String getColumnName(int col)
{
return columnNames[col];
}
public Object getValueAt(int row, int
col) {
return data[row][col];
}
public boolean isCellEditable(int
row, int col) {
return (col < 2);
}
public void setValueAt(Object value,
int row, int col) {
data[row][col] = (Double)value;
fireTableCellUpdated(row, col);
}
}
public class TableGUI extends JPanel implements
TableModelListener {
private static final long
serialVersionUID = 1L;
private JTable table;
public TableGUI() {
MyTableModel model = new MyTableModel();
model.addTableModelListener(this);
table = new JTable(model);
table.setPreferredScrollableViewportSize(
new Dimension(500, 70));
setLayout(new BorderLayout());
add(table.getTableHeader(),
BorderLayout.PAGE_START);
add(table, BorderLayout.CENTER);
}
public void
tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
if (column < 2) {
MyTableModel
model = (MyTableModel)e.getSource();
double
arg1 = (Double)model.getValueAt(row, column);
double
arg2 =
(Double)model.getValueAt(row,
(column + 1) % 2);
model.setValueAt(new
Double(arg1 + arg2), row, 2);
model.setValueAt(new
Double(arg1 * arg2), row, 3);
model.setValueAt(new
Double(arg1 - arg2), row, 4);
model.setValueAt(new
Double(arg1 / arg2), row, 5);
}
}
public static void main(String[] args)
{
AppFrame app = new AppFrame();
app.setTitle("Table GUI");
TableGUI gui = new TableGUI();
JScrollPane scrollPane = new
JScrollPane(gui.table);
app.setContentPane(scrollPane);
app.display();
}
}