1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class BaseDonnees extends Observable implements ActionListener {
private JButton btAdd;
private final JFrame f;
private final Table table;
private int count = 100;
public BaseDonnees() {
f = new JFrame("BaseDonnees");
initComponents();
table = new Table();
f.add(table);
addObserver(table);
f.setVisible(true);
}
private void initComponents() {
btAdd = new javax.swing.JButton("Add");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
btAdd.addActionListener(this);
f.getContentPane().add(btAdd, BorderLayout.PAGE_START);
f.setSize(400, 300);
f.setLocationRelativeTo(null);
}
public void actionPerformed(final ActionEvent e) {
Vector rowData = new Vector();
rowData.add("A" + count);
rowData.add("B" + count);
count++;
setChanged();
notifyObservers(rowData);
}
public static void main(final String[] args) {
Runnable gui = new Runnable() {
public void run() {
new BaseDonnees();
}
};
//GUI must start on EventDispatchThread:
SwingUtilities.invokeLater(gui);
}
}
class Table extends JPanel implements Observer {
private final DefaultTableModel table_model;
private final JTable jTable;
private final DataModel data_model = new DataModel();
private Vector cols;
public Table() {
cols = data_model.getHeaders();
Vector rows = data_model.getRows();
table_model = new DefaultTableModel(rows, cols);
jTable = new JTable(table_model);
setLayout(new BorderLayout());
add(new JScrollPane(jTable));
}
public void update(Observable ov, Object arg) {
Vector new_data = (Vector) arg;
// remarque que addRow contient déjà un fireTableRowsInserted:
table_model.addRow(new_data);
}
}
class DataModel {
private Vector headers;
private Vector rows;
public DataModel() {
headers = new Vector();
headers.add("Title 1");
headers.add("Title 2");
rows = new Vector();
Vector rowData = new Vector();
for (int i = 0; i < 4; i++) {
rowData.add("A" + i);
rowData.add("B" + i);
rows.add(rowData);
}
}
public Vector getRows() {
return rows;
}
public Vector getHeaders() {
return headers;
}
} |